【问题标题】:TypeError: jwt(...).unless is not a function when mocking with JestTypeError: jwt(...).unless 在使用 Jest 进行模拟时不是函数
【发布时间】:2021-03-09 19:40:15
【问题描述】:

我正在尝试模拟 express-jwt.unless 函数,目前有这个模拟设置来比较 JWT 与管理员和非管理员。在我们添加 .unless 之前,这一直是完美的,我不确定解决问题的最佳方法。

jest.mock("express-jwt", () => {
  return options => {
    return (req, res, next) => {
      receivedToken = req.headers.authorization.substring(7);
      req.user = { preferred_username: "tester" };
      next();
    };
  };
});

那是模拟。我尝试将其移入 const 并添加:mockFun.unless = jest.fn() 但无济于事。

谢谢

编辑:

我尝试过的事情之一如下:

jest.mock("express-jwt", () => {
  const mockFunc = () => {
    return (req, res, next) => {
      receivedToken = req.headers.authorization.substring(7);
      req.user = { preferred_username: "tester" };
      next();
    };
  };

  mockFunc.unless = jest.fn();

  return mockFunc
});

【问题讨论】:

  • 我尝试将其移入 const - 你到底做了什么?
  • @EstusFlask 进行了编辑以反映这一点

标签: javascript node.js unit-testing jestjs mocking


【解决方案1】:

unless 应该是 jwt() 返回的函数上的方法,而目前它是 jwt 本身上的方法。

应该是:

jest.mock("express-jwt", () => {
  const mockFunc = jest.fn((req, res, next) => {
   ...
  });

  mockFunc.unless = jest.fn((req, res, next) => {
   ...
  });

  return jest.fn(() => mockFunc);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 2019-11-02
    • 2020-06-09
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多