Jest Express 测试带参数的中间件

Jest Express testing middleware with arguments

我是 node 的新手,这是我第一次对应用程序进行单元测试。我用 Jest 伪造 Jest 函数的请求做得很好,如下所示

// Create a fake request
 const mockRequest = (sessionData, body) => ({
  session: { data: sessionData },
  body
});

// Create a fake response
 const mockResponse = () => {
  const res = {};
  res.status = jest.fn().mockReturnValue(res);
  res.json = jest.fn().mockReturnValue(res);
  return res;
};

const mockNext = () => {
  const next = jest.fn();
  return next;
};

所以我可以像下面这样使用它们

doSomething(req, res, next);
expect(res.status).toHaveBeenCalledWith(201);
//or
expect(next).toHaveBeenCalled();

这对所有情况都足够了,直到我发现我的授权中间件包含几个参数,所以我不能像下面那样传递假的 res 和 req

exports.isAllowedTo = (par1, par2) => {
    return async (req, res, next) => {
        try {
            //
            // Grant logic here that needs par1 and par2
            //

            if(granted)
                next();
            else
                return res.status(401).json({
                    error: "You don't have enough permission to perform this action"
                });

        } catch (err) {
            res.status(406).json({
                error: err.toString(),
            })
        }
    }
}

如果我使用模拟请求、res 和 next 测试 isAllowTo(req, res, next),那么我将缺少函数所需的 2 个参数。实际上,当我这样做时,函数 isAllowTo() 甚至都没有被调用。我不知道该如何处理。有什么建议或方法吗?

查看 https://github.com/nock/nock 这是一个专门用于模拟请求和响应的库,与单元 tests/jest 一起使用真的很容易。我个人认为编写自己的模拟实现不值得。

两个月后我意识到真正的问题是我在另一个函数内部测试一个函数。 所以首先我将函数存储在一个变量中,这样我就可以将它作为常规中间件进行测试。

test('Grant access if user role is allowed to', async () => {

    const isAllowToTester = userController.isAllowedTo(par1, par2);

    await isAllowToTester(req, res, next)

    expect(next).toHaveBeenCalled();

});

希望这对其他人有帮助。 归功于此