node.js - 如何为快速 session req.session.destroy() 编写简单的 Jest 模拟

标签 node.js unit-testing jestjs express-session

我正在编写一个具有简单注销突变的 grapqhl 服务器。当我运行服务器时,一切都按预期工作,我可以通过销毁 session 并清除 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 超时:

超时 - 在 jest.setTimeout 指定的 5000 毫秒超时内未调用异步回调。

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

我怀疑我需要编写一个更好的 Jest 模拟来更准确地模拟 context.req.session.destroy 内部的回调,但我无法弄清楚。

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

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

没有剪掉它。想法?

最佳答案

尝试

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

关于node.js - 如何为快速 session req.session.destroy() 编写简单的 Jest 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55168610/

相关文章:

unit-testing - 什么是 ON 单元?

Angular/Jasmine - 如果在 ngOnInit 上调用,Spies 是否工作?

javascript - 将 Jest 覆盖阈值添加到 create-react-app 项目

typescript - 在一个 npm 脚本中设置一个 env 变量,稍后可以在另一个脚本中访问该变量

node.js - ReactJs Jest :`jsdom 4. x 及以上版本仅适用于 io.js,不适用于 Node.jsT:

node.js - 如何在 Javascript (node.js) 开发人员模式下运行 Azure Application Insights

node.js - NodeJS Spawn 不触发参数

node.js - NodeJS 使用 node-crawler 或 simplecrawler 进行 Web 爬行

javascript - 从本地文件夹在 Windows 上安装 Node uglifyjs

unit-testing - 在 Unity3d 测试脚本中,如何从另一个类调用静态函数?