javascriptasync-awaitmocha.jschaichai-as-promised

Mocha.js: async function breaks the nested structure


When testing a result of async function, using mocha, the tests that comes after await pops out of the nested structure, like the first 2 tests below:

✓ email
✓ phone
current unit
    fetch data
    ✓ is 5==5

3 passing (10ms)

How can we make the tests to appear in their proper place?

The code:

const chai = require('chai');
chai.should();

describe ("current unit", async () => {    
    describe ("fetch data", async () => {    
        it ("is 5==5", () => { chai.expect(5).to.equal(5); });

        const UserData = await getUserData("UserName");

        it ("email", () => { UserData.email.should.equal("example@g.com"); });
        it ("phone", () => { UserData.phone.should.equal("+1 (800) 123 4567"); });
    });
});

function getUserData(param) { return new Promise(resolve => setTimeout(() => resolve({ email:"example@g.com",phone:"+1 (800) 123 4567" }), 1/*ms*/));}

Solution

  • Here is your test file using before

    const chai = require('chai');
    chai.should();
    
    describe ("current unit", async () => {    
        describe ("fetch data", async () => {    
            let UserData
            before(async () => {
                UserData = await getUserData("UserName");
            })
            it ("is 5==5", () => { chai.expect(5).to.equal(5); });
            it ("email", () => { UserData.email.should.equal("example@g.com"); });
            it ("phone", () => { UserData.phone.should.equal("+1 (800) 123 4567"); });
        });
    });
    
    function getUserData(param) { return new Promise(resolve => setTimeout(() => resolve({ email:"example@g.com",phone:"+1 (800) 123 4567" }), 1/*ms*/));}
    

    Here is the output for the above test

      current unit
        fetch data
          ✓ is 5==5
          ✓ email
          ✓ phone
    

    You can make the tests appear in their proper place by using a before expression in the "fetch data" test suite