【问题标题】:Mocha test fails before Promise resolves在 Promise 解决之前 Mocha 测试失败
【发布时间】:2021-04-24 23:42:35
【问题描述】:

我在 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 解决的承诺,但我的尝试都没有成功。

非常感谢任何帮助!提前致谢!

【问题讨论】:

  • 您可以尝试增加测试的超时时间(this.timeout(5000) 以查看承诺是否需要超过 2 秒才能完成。或者也许在startWithPlaylist 中记录时间戳,看看需要多长时间才能解决。
  • 这正是我一分钟前所做的!它正在工作。因为 promise 必须执行多个 http 请求,所以需要超过 2 秒的时间来解决。

标签: node.js async-await timeout mocha.js es6-promise


【解决方案1】:

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

你可以通过多种方式使用this.timeout(...)。文档here

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

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时使用parameters in command line

mocha test --timeout 4000

【讨论】:

    【解决方案2】:

    你真的定义了 arg.运行时的“id”?

    【讨论】:

    • 是的,我做到了。 (您可以在第一个 sn-p 中看到 id 为 3DiOnTOzRokGNlFaFUonCy)。
    • 尝试将输出放入变量中
    • 将其更改为 let output = await this.party.startWithPlaylist('3e8JNsQmYEXtfV7K1M0pAb') 并没有改变任何内容。
    • 我要对您使用的软件包进行更多研究。
    猜你喜欢
    • 2015-08-04
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多