I am relatively new to Mocha, Chai, and Unit Testing. I'm currently attempting to create a basic test to verify the presence of Authorization headers in the request that passes through my middleware function. Despite trying various approaches such as using TypeError
, throw()
, error messages, and Error
without success.... any assistance on this matter would be highly appreciated.
Middleware Function:
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);
}
};
Test Script:
it('Should throw an error if no auth header provided.', function () {
const req = {
get: function () {
return null;
},
};
expect(function () {
verify(req, {}, () => {});
}).to.throw();
});
Just for reference - Error handling in 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);
});