首页 > 解决方案 > 如何在 Mocha 异步单元测试中使用 afterEach?

问题描述

在下面的代码中,在测试中的 Promise 被解析并被afterEach()调用之前done()被调用。我希望它在测试完成后运行done()。这样做的正确方法是什么?

describe ("Some test", ()=>{
    afterEach(()=>{
        console.log("Done")
    })

    it("Does something", done=>{
        new Promise (resolve=>{
            let result = doSomething();
            assert.isOK(result);
            done();
        })
    })
})

标签: javascriptunit-testingasynchronousmocha.js

解决方案


这不是你在 Mocha 中使用 Promises 的方式。

Mocha 仅通过返回 Promise(不需要done())或使用async函数作为测试(隐式返回 Promise)来支持异步测试,如下所示:

describe ("Some test", ()=>{
    afterEach(()=>{
        console.log("Done")
    })

    it("Does something", async () => {
        const result = await someAsyncFunction();
        assert.isOK(result);
        // no need to return from this one, async functions always return a Promise.
    })
})

或者

describe ("Some test", ()=>{
    afterEach(()=>{
        console.log("Done")
    })

    it("Does something", done=>{
        // note the return
        return new Promise (resolve=>{
          doSomethingWithCallback(result => {
            assert.isOK(result);
            resolve(result);
          });
        })
    })
})

请注意,new Promise()在非低级代码中使用构造函数被视为反模式。有关更多详细信息,请参阅此问题:什么是显式承诺构造反模式以及如何避免它?


推荐阅读