Search code examples
node.jsasync-awaittimeoutmocha.jses6-promise

Mocha test fails before Promise resolves


I have a Mocha test in NodeJS:

it('Test', async () => {
    this.party = new Party('example_id');
    await this.party.startWithPlaylist('3e8JNsQmYEXtfV7K1M0pAb');
    assert.isTrue(this.party.getStreamingProvider().getAuth().getToken() !== undefined);
})

With this.party.startWithPlaylist being:

startWithPlaylist(id) {
    return new Promise(async (resolve, reject) => {
        assert.ok(id !== undefined);
        await this.start();
        let playlist = await this.songInfoProvider.getPlaylist(id);
        resolve();
    });
}

The code is working correctly, but my test is not. 2 Seconds after starting the test I get the error:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

After the error occurs startWithPlaylist finishes correctly but as it seems not in time for my test.

I've looked through Stackoverflow and found similar problems but none with an accepted answer or any other hint that works for me. I already tried to change the test from async to just waiting for the promise to resolve with .then but none of my attempts made it work.

I would really appreciate any help! Thanks in advance!


Solution

  • The problem here is the time that function needs to execute is higher than the timeout provided.

    Yo can chan using this.timeout(...) in multiple ways. Docs here

    One way is like this, but exists multiple options: suite/test/hook level...

    it('Test', async () => {
      this.party = new Party('example_id');
      await this.party.startWithPlaylist('3e8JNsQmYEXtfV7K1M0pAb');
      assert.isTrue(this.party.getStreamingProvider().getAuth().getToken() !== undefined);
    }).timeout(4000)
    

    or using parameters in command line when running mocha in this way:

    mocha test --timeout 4000