【问题标题】:How to test a GraphQl API? [closed]如何测试 GraphQl API? [关闭]
【发布时间】:2017-08-08 02:08:28
【问题描述】:

我需要编写一个功能测试套件(用于测试 GraphQl API)。测试套件将位于与 API 不同的存储库和容器中。

我想到的一种方法是在测试套件中使用 BDD 框架。该套件将在收到 HTTP 请求后运行所有 BDD 测试。

我正在考虑使用 Cucumber.js 作为 BDD 框架。我知道有npm test。我不确定我将如何执行测试。以这种方式使用单元测试框架感觉有点尴尬。这种方法有意义吗?

有什么工具可以做这样的事情?我愿意考虑各种语言和工具。

【问题讨论】:

  • 我没有经验给出足够好的答案,但这篇文章帮助了我medium.com/entria/…我已经尝试用我的实现来实现黄瓜这里是一个例子github.com/RedLeap/swapi-graphql-module/blob/… - 重申一下我'我不是一个有经验的测试人员,我只是想我会给我的两分钱,而不是让这个无人回答。如果您有任何问题,请告诉我:)

标签: testing functional-testing graphql


【解决方案1】:

Karate 是一个相对较新的 Web 服务测试自动化框架,由于 2 个特定功能,它恰好非常适合测试 GraphQL 响应

  • 文本操作:很容易内联 GraphQL 查询,从(可重用)文件和substitute placeholders 中读取它们
  • JsonPath 断言:虽然 GraphQL 响应是 JSON,但它们会根据请求动态变化(无固定模式),并且往往嵌套很深。空手道原生的 JsonPath 断言可以让你只关注你需要的块,并且可以用 JSON 形式表达预期的结果,可读性很强

这是一个很好的例子:graphql.feature,下面有一个 sn-p:

# 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 的 binary executable,而 Visual Studio Code 是 sufficient as an IDE。 JavaScript 程序员会特别有宾至如归的感觉,因为 Karate embeds a JavaScript runtime 和支持 'lenient' JSON(不需要双引号,不需要将 JSON 键括在引号中)。

编辑:这是一个团队在生产中使用它的文章的链接:https://www.codemotion.com/magazine/dev-hub/web-developer/graphql-testing-with-karate/

免责声明:此处为开发人员。

【讨论】:

    【解决方案2】:

    您可以将 npm test 与您想要的任何测试运行程序一起使用。我正在使用摩卡和柴。 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 调用,因为这会产生不必要的依赖关系。因此,如果测试中断,那么突然间就很难找出根本原因。

    【讨论】:

    • 代码中的graphql()是什么,是库函数吗?
    • @SunilLulla import {graphql} from 'graphql'
    猜你喜欢
    • 2017-10-10
    • 2018-10-28
    • 2018-05-11
    • 2019-04-27
    • 2020-10-28
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多