【问题标题】:How to Unit Test Graphql Resolver functions created using apollo-resolvers如何对使用 apollo-resolvers 创建的 Graphql Resolver 函数进行单元测试
【发布时间】:2019-03-14 23:21:42
【问题描述】:

我使用 'apollo-resolvers' npm 模块创建了解析器s(userresolver.js),如下所示。

import { createResolver } from 'apollo-resolvers';
import {  isInstance } from 'apollo-errors';

const baseResolver = createResolver(
  null,
  (root, args, context, error) => isInstance(error) ? error : new UnknownError()
);



const users = baseResolver.createResolver(
  (parent, args, { models, me } ) => {
         return Object.values(models.users);
  }
);

export default {
  Query: {
    users
  }
}

;

当我在启动服务器后测试查询时,这些也可以正常工作。

我现在想对解析器函数进行单元测试。

我不知道该怎么做。有人可以帮助我如何对解析器功能进行单元测试。我正在使用 mocha 和 chai 来测试我的项目。

【问题讨论】:

    标签: mocha.js graphql chai apollo-server


    【解决方案1】:

    你可以试试easygraphql-tester,它有一个方法可以帮助你测试解析器。

    Here 是它的文档。

    示例:

    解析器

    "use strict";
    
    const license = (__, args, ctx) => {
      const { key } = args;
    
      return {
        id: "1234",
        body: "This is a test license",
        description: `This is a description with key ${key}`
      };
    };
    
    module.exports = {
      Query: {
        license
      }
    };
    
    

    测试

    "use strict";
    
    const fs = require("fs");
    const path = require("path");
    const { expect } = require("chai");
    const EasyGraphQLTester = require("easygraphql-tester");
    
    const resolvers = require("../resolvers");
    const schemaCode = fs.readFileSync(
      path.join(__dirname, "..", "schema.gql"),
      "utf8"
    );
    
    describe("Test resolvers", () => {
      let tester;
      beforeAll(() => {
        tester = new EasyGraphQLTester(schemaCode, resolvers);
      });
    
      it("should return expected values", async () => {
        const query = `
          query GET_LICENSE($key: String!) {
            license(key: $key) {
              id
              body
              description
            }
          }
        `;
    
        const args = {
          key: "1234"
        };
    
        const result = await tester.graphql(query, {}, {}, args);
        expect(result.data.license.id).to.be.eq("1234");
        expect(result.data.license.body).to.be.eq("This is a test license");
        expect(result.data.license.description).to.be.eq(
          `This is a description with key ${args.key}`
        );
      });
    });
    

    【讨论】:

    • 不确定这是否满足要求。用于单元测试解析器代码。似乎是用于集成/E2E 测试。
    • 也许this example 会有用!
    猜你喜欢
    • 2019-12-19
    • 2018-06-19
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2023-03-26
    • 2018-04-02
    • 2021-08-21
    • 2021-01-29
    相关资源
    最近更新 更多