Reputation: 2304
I'm trying to test an async middleware auth function using the done function of Mocha. However, it seems that the test completes before the done function is called in the async call. Isn't the test supposed to wait until the done callback is called?
The middlware:
const AuthMiddleware = (req: Request, res: Response, next: NextFunction) => {
const token = getToken(req)
if (token === undefined) {
res.status(401)
next()
}
jwt.verify(token, getSigningKey, (err, decodedToken) => {
if (err) {
res.status(401)
next()
}
})
}
My test:
describe("AuthMiddleware", () => {
it("Should return 401 if token is expired", (done) => {
const options = { headers: { authorization: "Bearer " + expiredToken } }
const req = mockReq(options) as Request
const res = mockRes() as Response
AuthMiddleware(req, res, done)
expect(res.status).to.have.been.calledWith(401)
}).timeout(10000)
})
Upvotes: 0
Views: 285
Reputation: 24
You are treating done() as next(). Done is used to end the test while next is used in your middle ware
describe("AuthMiddleware", () => {
it("Should return 401 if token is expired",async (done) => {
const options = { headers: { authorization: "Bearer " + expiredToken } }
const req = mockReq(options) as Request
const res = mockRes() as Response
await AuthMiddleware(req, res, done)
expect(res.status).to.have.been.calledWith(401)
}).timeout(10000)
})
Upvotes: 1