Jest Express使用参数测试中间件 [英] Jest Express testing middleware with arguments

查看:174
本文介绍了Jest Express使用参数测试中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Node还是很陌生,这是我第一次单元测试一个应用程序.我用Jest伪造了如下所示的Jest函数的请求,一切都很好

I'm pretty new to node and this is my first time unit testing an app. I'm doing well with Jest faking the request with Jest function as below

// 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;
};

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

So I can use them like follows

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

在所有情况下就足够了,直到我发现我的授权中间件包含几个参数,这样我才能按以下方式传递假的res和req

That's enough for all the cases until I found that my authorisation middleware includes a couple of parameters so I can not pass the fake res and req as below

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(),
            })
        }
    }
}

如果我用模拟req,res和next测试isAllowTo(req, res, next),则缺少该功能所需的2个参数.实际上,当我执行此操作时,甚至没有调用函数isAllowTo().我不知道该如何处理.有什么建议或方法吗?

If I test isAllowTo(req, res, next) with the mock req, res and next then I'm missing the 2 parameters needed by the function. Actually when I do this, the function isAllowTo() is not even called. I don't know how to deal with that. Any suggestion or approach?

推荐答案

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

Two months later I realized that the real problem is that I'm testing a function inside of another function. So firstly I store the function in a variable so I can test it as a regular middleware.

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

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

    await isAllowToTester(req, res, next)

    expect(next).toHaveBeenCalled();

});

希望这对其他人有帮助. 对此帖子

Hope this helps someone else. Credits to this post

这篇关于Jest Express使用参数测试中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆