首页 > 解决方案 > 在 Promise 解决之前 Mocha 测试失败

问题描述

我在 NodeJS 中有一个 Mocha 测试:

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

存在this.party.startWithPlaylist

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

代码工作正常,但我的测试没有。开始测试后 2 秒出现错误:

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

错误发生后startWithPlaylist正确完成,但似乎没有及时进行我的测试。

我查看了 Stackoverflow 并发现了类似的问题,但没有一个可以接受的答案或任何其他适合我的提示。我已经尝试将测试从async只是等待承诺解决,.then但我的尝试都没有成功。

我真的很感激任何帮助!提前致谢!

标签: node.jsasync-awaittimeoutmocha.jses6-promise

解决方案


这里的问题是函数需要执行的时间高于提供的超时时间。

哟可以this.timeout(...)以多种方式使用。文档在这里

一种方式是这样,但存在多个选项:套件/测试/挂钩级别...

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

或以这种方式运行 mocha 时在命令行中使用参数:

mocha test --timeout 4000

推荐阅读