如何使用TypeScript和mocha进行异步/等待测试

时间:2016-04-12 10:31:11

标签: typescript async-await mocha

我有一个简单的异步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提供一个简单的例子吗?

2 个答案:

答案 0 :(得分:8)

尝试像这样定义你的测试......(同时删除完成调用)

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

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

最佳做法是避免使用箭头功能来定义测试,否则您无法从测试中访问正确的this上下文(即您无法执行调用等操作测试代码中的this.title

答案 1 :(得分:0)

const mochaAsync = (fn: any) => {
    return (done: any) => {
        fn.call()
            .then(done, (err: Error) => { done(err); });
    };
};

摩卡> = 3.0.0

{{1}}

Testing Asynchronous Code with MochaJS and ES7 async/await