2017-03-16 84 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。