如何使用Jest测试身份验证中间件



我正在学习nodejs,大部分情况下进展顺利。我试着学习如何在考试中用笑话来嘲弄别人。我看了很多教程,但我似乎无法理解。

我有这个中间件,用于受保护的路由。。。

import jwt from 'jsonwebtoken';
export default function (req, res, next) {
const token = req.header('x_auth-token');
if (!token) return res.status(401).json({ message: 'Access denied' });
try {
const verified = jwt.verify(token, process.env.TOKEN_SECRET);
req.user = verified;
next();
} catch (err) {
return res.status(400).send('Invalid Token');
}
}

从我读到的内容来看,我认为我应该采取的方法是这样的。。。

import verifyToken from '../middleware/verifyToken';
test('verifyToken', () => {
expect.assertions(1);
const res = {};
const req = {};
const next = (err) => expect(err).toBeFalsy();
verifyToken(req, res, next);
});

然而,这显然是行不通的。

那么,我如何用令牌模拟请求标头呢?

因此,如果我们完全忘记了req、res在现实世界中是什么,那么它们显然是请求和响应,但我们现在就忘了这一点。

在您的真实代码中,您有token = req.header("x_auth-token")

因此,在我们的测试代码中,我们需要在req对象中有一些东西,当用这些参数调用时,这些东西会返回您想要的东西。

所以我想说。

const req = {
header: jest.fn(() => 'myAuthToken')
}

CCD_ 2生成了模拟函数,并且当调用它时,它将始终返回字符串CCD_。

然后,我们可以通过添加来检查是否使用正确的参数调用了标头函数

expect(req.header).toHaveBeenCalledWith("x_auth-token")

您还需要模拟jwt.verify,因为您没有测试jwt.verify的工作原理,因为它将包含自己的测试。你会想确保你使用正确的的响应

要做到这一点,请查看这个堆栈溢出问题

最后,我将把下一个设置为模拟函数

mockNext = jest.fn()

然后我们可以说在测试

expect(mockNext).toHaveBeenCalled()

所以我很难理解如何模拟函数。我根据奥利·帕格的回答在谷歌上搜索了很多,这就是我想到的。

import jwt from 'jsonwebtoken';
import verifyToken from '../middleware/verifyToken';
import { uIds } from './testdata/userTestData';
describe('verifyToken tests', () => {
const { uid1 } = uIds;
it('Should pass the userId to the request object if token is verified', () => {
const res = {};
const req = {
header: jest.fn(() => 'myAuthToken'),
};
const next = jest.fn();
const verify = jest
.spyOn(jwt, 'verify')
.mockReturnValueOnce({ userId: String(uid1) });
verifyToken(req, res, next);
expect(req.header).toHaveBeenCalledWith('x_auth-token');
expect(req.user).toEqual({ userId: String(uid1) });
expect(next).toHaveBeenCalled();
});
it('Should deny access if token is not present in header', () => {
const res = {
json(msg) {
expect(msg).toEqual({ message: 'Access denied' });
},
status(responseStatus) {
expect(responseStatus).toEqual(401);
return this;
},
};
const req = {
header: jest.fn(),
};
const next = jest.fn();
verifyToken(req, res, next);
expect(req.header).toHaveBeenCalledWith('x_auth-token');
expect(req.user).not.toEqual({ userId: String(uid1) });
});
it('Should deny access if token is invalid', () => {
const res = {
send(text) {
expect(text).toEqual('Invalid Token');
},
status(responseStatus) {
expect(responseStatus).toEqual(400);
return this;
},
};
const req = {
header: jest.fn(() => 123),
};
const next = jest.fn();
const verify = jest.fn();
verifyToken(req, res, next);
expect(req.header).toHaveBeenCalledWith('x_auth-token');
expect(req.user).not.toEqual({ userId: String(uid1) });
});
});

这通过了测试。但是我不确定这个测试的有效性。

最新更新