我正在尝试使用Mocha的done函数测试异步中间件auth函数。但是,似乎在异步调用中调用完函数之前,测试已完成。测试不应该等到完成的回调被调用吗?
中间件:
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()
}
})
}
我的测试:
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)
})
答案 0 :(得分:1)
您将done()视为next()。完成用于结束测试,而下一步用于中间件
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)
})