Jest Express 使用参数测试中间件

Nat*_*abe 7 unit-testing middleware node.js express jestjs

我对 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;
};
Run Code Online (Sandbox Code Playgroud)

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

doSomething(req, res, next);
expect(res.status).toHaveBeenCalledWith(201);
//or
expect(next).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)

对于所有情况来说这已经足够了,直到我发现我的授权中间件包含几个参数,所以我无法传递虚假的 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(),
            })
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Nat*_*abe 3

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

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

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

    await isAllowToTester(req, res, next)

    expect(next).toHaveBeenCalled();

});
Run Code Online (Sandbox Code Playgroud)

希望这对其他人有帮助。归功于这篇文章