如何测试 GraphQl API? [英] How to test a GraphQl API?
问题描述
我需要编写一个功能测试套件(将测试 GraphQl API).测试套件将位于与 API 不同的存储库和容器中.
I need to write a functional test suite (that will test a GraphQl API). The test suite will be in a separate repo and container from the API.
我想到的一种方法是在测试套件中使用 BDD 框架.该套件将在收到 HTTP 请求后运行所有 BDD 测试.
One approach I thought of would be to use a BDD framework within the test suite. The suite would run all the BDD tests after receiving a HTTP request.
我正在考虑使用 Cucumber.js 作为 BDD 框架.我知道有 npm test
.我不确定我将如何执行测试.这样使用单元测试框架感觉有点别扭.这种方法有意义吗?
I was considering using Cucumber.js as the BDD framework. I know there is npm test
. I am not sure how I will execute the tests. It feels a bit awkward to use a unit testing framework in this way. Does this approach make sense?
有什么工具可以做这样的事情?我愿意考虑各种语言和工具.
What tooling exists to do something like this? I am open to consider various languages and tools.
推荐答案
Karate 是一个相对较新的由于 2 个特定功能,Web 服务测试自动化框架恰好非常适合测试 GraphQL 响应
Karate is a relatively new web-services test-automation framework that happens to be well suited for testing GraphQL responses because of 2 specific capabilities
- 文本操作:很容易内联 GraphQL 查询,从(可重复使用的)文件和 替换占位符
- JsonPath 断言:虽然 GraphQL 响应是 JSON,但它们会根据请求(无固定架构)动态变化,并且往往是深度嵌套的.Karate 原生的 JsonPath 断言让你可以只关注你需要的块,并且可以用快捷的 JSON 形式表达预期的结果,非常易读
这是一个很好的例子:graphql.feature
下面是一个片段:
Here is a good example: graphql.feature
with a snippet below:
# 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 团队,Karate 提供了一个 二进制可执行文件 只需要 JRE,而 Visual Studio Code 是 足够作为一个 IDE.JavaScript 程序员会特别有宾至如归的感觉,因为 Karate 嵌入 JavaScript 运行时 和支持 'lenient' JSON(不需要双引号,不需要用引号将 JSON 键括起来).
For non-Java teams, Karate provides a binary executable that only requires the JRE, and Visual Studio Code is sufficient as an IDE. JavaScript programmers will especially feel at home because of how Karate embeds a JavaScript runtime and supports 'lenient' JSON (no double-quotes needed, no need to enclose JSON keys in quotes).
这是一个团队在生产中使用它的文章的链接:https://www.codemotion.com/magazine/dev-hub/web-developer/graphql-testing-with-karate/
here's a link to an article by a team using it in production: https://www.codemotion.com/magazine/dev-hub/web-developer/graphql-testing-with-karate/
免责声明:在此开发.
这篇关于如何测试 GraphQl API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!