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

How write simple Jest mock for express-session's req.session.destroy()

我正在编写一个具有简单注销变更的 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();
  });

});

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

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

原因是上述解析器的等待部分将挂起,因为它的 promise.resolve() 永远不会被执行。所以我的控制台将显示 "THIS WILL LOG",但永远不会显示 "NEVER HERE BEFORE TIMEOUT"。

我想我需要写一个更好的笑话模拟来更准确地模拟上下文中的回调。req.session.destroy,但我想不通。

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

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

不剪了。想法?

尝试

context.req.session.destroy = jest
      .fn()
      .mockImplementation((fn) => fn(false));