mocha done()和async await的矛盾问题

Alo*_*lon 5 javascript unit-testing mocha.js async-await typescript

我有以下测试用例:

it("should pass the test", async function (done) {
        await asyncFunction();
        true.should.eq(true);
        done();
    });
Run Code Online (Sandbox Code Playgroud)

运行它断言:

错误:分辨率方法过分指定.指定回调 返回Promise; 不是都.

如果我删除该done();语句,它断言:

错误:超出2000ms的超时.对于异步测试和挂钩,确保调用"done()"; 如果返回Promise,请确保它已解决.

如何解决这个悖论?

T.J*_*der 13

您还需要删除done参数,而不仅仅是对它的调用.像Mocha这样的测试框架会查看函数的参数列表(或者至少是它的arity),以了解您是在使用done还是类似.

采用摩卡3.5.3,这对我的作品(不得不改变true.should.be(true),以assert.ok(true)作为前抛出错误):

const assert = require('assert');

function asyncFunction() {
    return new Promise(resolve => {
        setTimeout(resolve, 10);
    });
}

describe('Container', function() {
  describe('Foo', function() {
    it("should pass the test", async function () {
        await asyncFunction();
        assert.ok(true);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

但如果我补充done:

describe('Container', function() {
  describe('Foo', function() {
    it("should pass the test", async function (done) {  // <==== Here
        await asyncFunction();
        assert.ok(true);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

......然后我明白了

错误:超出2000ms的超时.对于异步测试和挂钩,确保调用"done()"; 如果返回Promise,请确保它已解决.