2017-03-16 36 views
7

我需要編寫一個功能測試套件(這將測試GraphQl API)。測試套件將獨立於API的回購和容器中。如何測試GraphQl API?

我想到的一種方法是在測試套件中使用BDD框架。該套件收到HTTP請求後將運行所有BDD測試。

我正在考慮使用Cucumber.js作爲BDD框架。我知道有npm test。我不知道我將如何執行測試。以這種方式使用單元測試框架感覺有點尷尬。這種方法有意義嗎?

有什麼工具可以做這樣的事情?我很樂意考慮各種語言和工具。

+0

我沒有經驗給出足夠好的答案,但這篇文章幫助我了https://medium.com/entria/testing-a-graphql-server-using-jest-4e00d0e4980e#.qohdw3wuz我試過了實施黃瓜與我在這裏實施是一個例子https://github.com/RedLeap/swapi-graphql-module/blob/5da487bf28897aa228d937712dabfd6580cb301d/features/planets.feature - 只是重申我不是一個有經驗的測試者只是認爲我' d給我兩分錢,而不是讓這個沒有答案。如果你有任何問題,請讓我知道:) –

回答

1

你可以用任何你想要的測試跑步者使用npm測試。我正在使用摩卡和柴。 Jest可能會更好一些,因爲我相信它可能是最先進的測試套件。您只需創建測試就像任何端點測試一樣。

 it('should be null when user is not logged in', async() => { 
     const query = ` 
      query { 
      user(id: "") { 
       username 
       email 
      } 
      } 
     ` 

    const rootValue = {}; 
    const context = {}; 

    const result = await graphql(schema, query, rootValue, context); 
    const { data } = result; 

    expect(data.user).to.equal(null); 
    }); 

非常簡單的方法來測試它。你也運行一個before語句將相關用戶插入你的數據庫。保持測試套件分離的問題是您需要直接訪問數據庫。您的測試不應該依賴於其他API調用,因爲這會造成不必要的依賴關係。所以如果一個測試中斷,那麼突然之間的根本原因很難弄清楚。

0

Karate是一個相對較新的Web服務測試自動化框架,出現這種情況是非常適合,因爲2種特定能力

測試GraphQL反應
  • 文本操作:很容易在網上GraphQL查詢,從(可重用)文件中讀取它們並且substitute placeholders
  • JsonPath斷言:雖然GraphQL響應是JSON,但它們根據請求動態變化(沒有固定模式)並且傾向於深度嵌套。空手道的本地JsonPath斷言允許你只注重你所需要的塊,你可以表達在短切JSON形式,這是非常具有可讀性

這裏是一個很好的例子,預計業績:graphql.feature下面的代碼段:

# you can also read this query from a file 
Given text query = 
""" 
{ 
    pokemon(name: "Pikachu") { 
    id 
    number 
    name 
    attacks { 
     special { 
     name 
     type 
     damage 
     } 
    } 
    } 
} 
""" 
And request { query: '#(query)' } 
When method post 
Then status 200 

# json-path makes it easy to focus only on the parts you are interested in 
# which is especially useful for graph-ql as responses tend to be heavily nested 
* match $.data.pokemon.number == '025' 

# the '..' wildcard is useful for traversing deeply nested parts of the json 
* def attacks = get[0] response..special 
* match attacks contains { name: 'Thunderbolt', type: 'Electric', damage: 55 } 

即使空手道需要Java運行時,語法是Cucumber/Gherkin是中性語言,你可以輕鬆地添加空手道測試和reports到現有的持續集成設置。由於Karate embeds a JavaScript runtime和支持'寬鬆'JSON(不需要雙引號,不需要在引號中包含JSON密鑰),JavaScript程序員尤其會感到賓至如歸。

聲明:dev here。