node.js - 如何模拟 Express JWT except 函数?

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

我正在使用 Express 和 Express-JWT。

在 Express() 实例中我使用:

const api = express()
api.use(jwt({
 // my options
}))

为了在测试中模拟这一点,我使用 mocks\express-jwt\index.js 文件,其中包含:

const jwt = jest.fn().mockImplementation(options => (req, res, next) => {
  // set dummy req.user and call
  next()
})

module exports = jwt

这一切都运行良好。 现在我想跳过根端点的 JWT,因此我将 jwt 用法更改为:

api.use(jwt({
  // my options
}).unless({path:['/']}))

在我的模拟文件中我添加了:

jwt.unless = jest.fn().mockImplementation(options => (req, res, next) => {
  next()
})

但是,测试现在总是失败,function except is not Defined

有人知道如何模拟这个除非行为吗?

最佳答案

除非被用作调用jwt结果的属性

因此,要模拟它,请将 unless 模拟添加为 jwt 模拟返回的函数的属性:

const jwt = jest.fn().mockImplementation(options => {
  const func = (req, res, next) => {
    // set dummy req.user and call
    next();
  };
  func.unless = jest.fn().mockImplementation(options => (req, res, next) => {
    next();
  });
  return func;
});

module.exports = jwt;

关于node.js - 如何模拟 Express JWT except 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55517098/

相关文章:

javascript - 在 db.open() 回调中使用导出 - mongoose/express

node.js - 如何将对象写入流?

unit-testing - 如何对 U-SQL 脚本进行单元测试?

validation - Jersey 自定义验证器单元测试

java - 如何为此类编写junit测试用例

javascript - 弃用警告 : Unhandled promise rejections are deprecated

javascript - Mongoose - 通过回调函数返回设置虚拟值

javascript - 使用nodejs在目录中递归获取所有目录

node.js - 当我尝试将属性更新为 null 时,findByIdAndUpdate 抛出强制转换错误

javascript - 避免在 javascript 中循环多次返回 - async/await 以解决回调金字塔或回调 hell ,