【问题标题】:how do async/await testing with TypeScript and mocha如何使用 TypeScript 和 mocha 进行异步/等待测试
【发布时间】:2016-04-12 10:31:11
【问题描述】:

我有一个简单的异步 mocha 测试,但似乎从未调用过 done() 回调。

describe("RiBot", function() {
  it("should start with a random topic", async (done) => {
    await RiBot.init();
    let topic = RiBot.getTopic("testuser")
    assert.equal(topic, "FAILHERE");
    done()
  })
})

在这种情况下,断言应该失败,但我只是得到一个超时。

  RiBot
  RibotTest topic +0ms undefined
    1) should start with a random topic


  0 passing (2s)
  1 failing

  1) RiBot should start with a random topic:
     Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

编辑:当我使用断言作为标准 JS 代码运行时:

async function testRiBot() {
  try {
    await RiBot.init()
    let topic = RiBot.getTopic("testuser")
    debug('topic', topic)
    assert.equal(topic, "FAILHERE", 'fail match on topic');
  } catch(err) {
    debug("err", err, err.stack)
  }
}

我确实得到了一个异常作为错误抛出。

  RibotTest err +2ms { [AssertionError: fail match on topic]
  name: 'AssertionError',
  actual: 'undefined',
  expected: 'FAILHERE',
  operator: '==',
  message: 'fail match on topic',
  generatedMessage: false } AssertionError: fail match on topic
    at /Users/dc/dev/rikai/boteditor/test/RiBot_test.js:19:20
    at next (native)
    at fulfilled (/Users/dc/dev/rikai/boteditor/test/RiBot_test.js:4:58)
    at process._tickCallback (node.js:412:9)

有人可以提供一个使用打字稿 async/await 和 mocha 的简单示例吗?

【问题讨论】:

  • 你有没有想过@dcsan?

标签: typescript async-await mocha.js


【解决方案1】:

尝试像这样定义您的测试...(同时删除您的 done 调用)

it('should start with a random topic', async function () {
    // ...
});

请注意,如果您的测试返回 Promise,那么 mocha 框架将寻找要解决或拒绝的 Promise,而不是 done 回调。注意异步函数总是返回一个 Promise。

此外,最好避免使用箭头函数来定义测试,否则您将无法从测试中访问正确的 this 上下文(即,您无法在测试代码中执行诸如调用 this.title 之类的操作)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2016-04-05
    • 1970-01-01
    • 2014-02-06
    • 2014-03-19
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多