【问题标题】:How to make dummy context when testing graphql resolvers?测试graphql解析器时如何制作虚拟上下文?
【发布时间】:2020-09-25 09:31:55
【问题描述】:

我想测试一些 graphql 突变。但我不确定在编写测试时要给出什么作为上下文。例如,我想调用 createPost 突变:

it('admin should create a post', async () => {
    await createPost(
      null,
      {
        title: 'How to write a blog post',
        body: 'lorem ipsum dollar emmet',
        published: true,
      },
      dummyContext
    ).should.be.fulfilled;
  });

这里作为一个 dummyContext 我使用这个:

  const dummyContext = {
    request: { get: () => token },
  };

但是,它不起作用。里面createPost突变logincheker方法被调用:

export async function loginChecker({ request }) {
  const Authorization = request.get('Authorization');
  if (Authorization) {
    const token = Authorization.replace('Bearer ', '');
    const userInJwt = jwtValidator(token);
    const user = await prisma.user.findOne({ where: { id: userInJwt.id } });
    if (!user) {
      throw new Error('Not Authorized');
    }
    return user;
  }
}

我在运行测试用例时遇到了这个错误

AssertionError: expected promise to be fulfilled but it was rejected with 'TypeError: Authorization.replace is not a function

【问题讨论】:

    标签: javascript graphql prisma prisma-graphql nexus-prisma


    【解决方案1】:

    如果您正在寻找集成测试,则无需模拟上下文。正如我创建的here 一样,您可以直接针对实际数据库运行服务器。在__tests__ 文件夹中,我已经针对实际服务器运行了它,因此您无需模拟上下文,可以直接针对数据库调用 API。

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2018-11-03
      • 1970-01-01
      • 2011-08-04
      • 2020-12-09
      • 2020-04-05
      • 2019-02-26
      • 1970-01-01
      • 2012-05-18
      相关资源
      最近更新 更多