我对 Mocha、Chai 和单元测试有点陌生。我正在尝试编写一个基本测试来检查通过我的中间件发出的请求中是否存在授权标头。我已经尝试了一些事情,从传递
TypeError
到throw()
以及消息和Error
没有运气......任何帮助将不胜感激。
我的中间件
exports.verify = async (req, res, next) => {
try {
const headers = req.get('Authorization');
let decodedToken;
if (!headers) {
const error = new Error('Not Authenticated');
error.statusCode = 401;
throw error;
}
const token = headers.split(' ')[1];
try {
decodedToken = jwt.verify(token, SECRET);
} catch (err) {
err.statusCode = 500;
throw err;
}
if (!decodedToken) {
const error = new Error('Not Authenticated');
error.statusCode = 401;
throw error;
}
req.userUid = decodedToken.userUid;
const queryRef = await users.where('uid', '==', req.userUid).get();
if (queryRef.empty) {
const error = new Error('Not Authenticated');
error.statusCode = 401;
throw error;
}
next();
} catch (err) {
log.error(err);
next(err);
}
};
我的测试
it('Should throw an error if no auth header provided.', function () {
const req = {
get: function () {
return null;
},
};
expect(function () {
verify(req, {}, () => {});
}).to.throw();
});
以防万一 - app.ts 的错误处理
app.use((err, req, res, next) => {
const status = err.statusCode || 500;
const message = err.message;
const data = err.data || [];
const userUid = req.userUid;
const stack = err.stack;
log.error(`STATUS: ${status} - MESSAGE: ${message} - STACK: ${stack}`);
res.status(status).json(message);
});
谢谢大家的提示。经过更多的挖掘之后,这就过去了。
将测试更改为:
我的测试
it('Should throw an error if no auth header provided.', function (done) {
const req = {
get: function () {
return null;
},
};
const callback = (err) => {
if (err && err instanceof Error && err.message === 'Not Authenticated') {
// test passed, called with an Error arg
done();
} else {
// force fail the test, the `err` is not what we expect it to be
done(new Error('Assertion failed'));
}
};
verify(req, {}, callback);
});