【问题标题】:Mocha test express async middleware done not working摩卡测试快递异步中间件不工作
【发布时间】:2019-09-29 11:28:12
【问题描述】:

我正在尝试使用 Mocha 的 done 功能测试异步中间件身份验证功能。但是,似乎测试在异步调用中调用 done 函数之前完成。测试不应该等到调用完成回调吗?

中间件:

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)
})

【问题讨论】:

    标签: node.js express mocha.js


    【解决方案1】:

    您将 done() 视为 next()。 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)
    

    })

    【讨论】:

    • 我认为这是在中间件中使用 done 的默认方法。您对我在这种情况下如何以正确的方式应用有什么建议吗?
    • 请试试这个修改后的代码。当函数需要时间来执行某些操作并且之后其余代码可以使用该数据时,使用异步等待。否则其余代码将给出错误,因为需要的内容不存在,这是应用 await 的函数的输出。
    • 我听从了你的建议,并将中间件逻辑包装在一个 Promise 中,该 Promise 会在下一个函数调用之前在两个地方中的任何一个处解析。它完美地工作。谢谢。
    猜你喜欢
    • 2018-05-24
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2017-07-29
    • 2013-07-11
    • 1970-01-01
    • 2013-05-24
    • 2018-02-03
    相关资源
    最近更新 更多