如何为快递会话的req.session.destroy()写简单的Jest模拟

问题描述 投票:0回答:1

我正在编写一个具有简单注销突变的grapqhl服务器。当我运行服务器时,一切都按预期工作,我可以通过销毁会话并清除cookie来注销。

这是解析器:

export default async (root, args, context) => {

  console.log("THIS WILL LOG")
  await new Promise((res, rej) =>
    context.req.session.destroy(err => {
      if (err) {
        return rej(false);
      }
      context.res.clearCookie("qid");
      return res(true);
    })
  );
  console.log("NEVER HERE BEFORE TIMEOUT");

  // 4. Return the message
  return {
    code: "OK",
    message: "You have been logged out.",
    success: true,
    item: null
  };
};

我正在尝试编写一个简单的测试,以验证req.session.destroy和res.clearCookie函数是否实际被调用。此时我没有尝试测试cookie是否实际被清除,因为我实际上并没有启动服务器,我只是测试graphql解析器是否正确运行并且它调用了正确的函数。

这是我测试的一部分:

describe("confirmLoginResolver", () => {
  test("throws error if logged in", async () => {
    const user = await createTestUser();

    const context = makeTestContext(user.id);
    context.req.session.destroy = jest
      .fn()
      .mockImplementation(() => Promise.resolve(true));
    context.res.clearCookie = jest.fn();

    // this function is just a helper to process my graphql request.
    // it does not actually start up the express server
    const res = await graphqlTestCall(
      LOGOUT_MUTATION, // the graphql mutation stored in a var
      null, // no variables needed for mutation
      null // a way for me to pass in a userID to mock auth state,
      context // Context override, will use above context
    );
    console.log(res);
    expect(context.req.session.destroy).toHaveBeenCalled();
    // expect(res.errors.length).toBe(1);
    // expect(res.errors).toMatchSnapshot();
  });

});

同样,在实际运行服务器时一切正常。问题是当我尝试运行上面的测试时,我总是得到一个jest超时:

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

原因是上面的解析器的await部分会挂起,因为它的promise.resolve()永远不会被执行。因此我的控制台将显示“这将记录”,但永远不会“永远不会在这里”。

我怀疑我需要编写一个更好的jest模拟来更准确地模拟context.req.session.destroy中的回调,但我无法弄明白。

我有什么想法可以在这里编写更好的模拟实现吗?

context.req.session.destroy = jest
      .fn()
      .mockImplementation(() => Promise.resolve(true));

不削减它。思考?

node.js unit-testing jestjs express-session
1个回答
2
投票

尝试

context.req.session.destroy = jest
      .fn()
      .mockImplementation((fn) => fn(false));
© www.soinside.com 2019 - 2024. All rights reserved.