如何使用 await 测试带有 mocha 的异步代码

How to test async code with mocha using await

如何使用 mocha 测试异步代码?我想在 mocha

中使用多个 await
var assert = require('assert');

async function callAsync1() {
  // async stuff
}

async function callAsync2() {
  return true;
}

describe('test', function () {
  it('should resolve', async (done) => {
      await callAsync1();
      let res = await callAsync2();
      assert.equal(res, true);
      done();
      });
});

这会产生以下错误:

  1) test
       should resolve:
     Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
      at Context.it (test.js:8:4)

如果我删除 done() 我得到:

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

Mocha supports Promises out-of-the-box; You just have to return the Promiseit() 的回调。

如果 Promise 解决,则测试通过。 相反,如果 Promise 拒绝则测试失败。就这么简单。

现在,因为 async functions always implicitly return a Promise 你可以这样做:

async function getFoo() {
  return 'foo'
}

describe('#getFoo', () => {
  it('resolves with foo', () => {
    return getFoo().then(result => {
      assert.equal(result, 'foo')
    })
  })
})

您的 it 不需要 done 也不需要 async

不过,如果你还是坚持使用async/await:

async function getFoo() {
  return 'foo'
}

describe('#getFoo', () => {
  it('returns foo', async () => {
    const result = await getFoo()
    assert.equal(result, 'foo')
  })
})

无论哪种情况,不要done声明为参数

如果您使用上述任何方法,您需要从您的代码中完全删除 done。将 done 作为参数传递给 it() 向 Mocha 暗示您打算最终调用它。

同时使用 Promise done 将导致:

Error: Resolution method is overspecified. Specify a callback or return a Promise; not both

done方法仅用于测试基于回调或基于事件的代码。如果您正在测试基于 Promise 或 async/await 的函数,则不应使用它。