如何将 afterEach 与 Mocha 异步单元测试一起使用?

How to use afterEach with Mocha async unit tests?

在下面的代码中,afterEach() 之前被调用 测试中的承诺已经解决并且 done() 被调用。在使用 done() 完成测试后,我希望它成为 运行。正确的做法是什么?

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

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

我猜下面的(运行在整个测试中承诺 运行)做了我想要的,但肯定有更好的方法..?

let testPromiseChain = Promise.resolve();

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

    })

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

            })

    })
})

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

Mocha 仅通过返回 Promise(不需要 done())或使用 async 函数作为测试(隐式 returns 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() 构造函数被视为反模式。有关详细信息,请参阅此问题:What is the explicit promise construction antipattern and how do I avoid it?