TLP
TLP

Reputation: 1288

How to use afterEach with Mocha async unit tests?

In the code below, afterEach() is called before the promises in the tests have been resolved and done() is called. I want it to run after the tests have been completed with done(). What is the right way to do that?

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

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

Upvotes: 1

Views: 2681

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 174977

That's not how you use Promises with Mocha.

Mocha supports asynchronous tests just by returning a Promise (no need for done()), or by using an async function as the test (which implicitly returns a Promise), like so:

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

or

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

Note that using the new Promise() constructor in non-low-level code is considered an antipattern. See this question for more details: What is the explicit promise construction antipattern and how do I avoid it?

Upvotes: 2

TLP
TLP

Reputation: 1288

I guess the below (running a promise throughout the entire test run) does what I want but surely there has to be a better way..?

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

            })

    })
})

Upvotes: -1

Related Questions