首页 文章

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

提问于
浏览
3

我有以下测试用例:

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

运行它断言:

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

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

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

如何解决这个悖论?

1 回答

  • 8

    您还需要删除 done 参数,而不仅仅是对它的调用 . 像Mocha这样的测试框架使用 done 或类似功能查看函数's parameter list (or at least its arity) to know whether you' .

    使用Mocha 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);
        });
      });
    });
    

    但如果我添加 done

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

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

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

相关问题