如何在TypeScript和mocha中使用async/await进行测试

5

我有一个简单的异步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)

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

1个回答

10

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

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

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接