微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有以下测试用例:

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

运行它断言:

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

如果我删除done();声明,它声称:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure
“done()” is called; if returning a Promise, ensure it resolves.

如何解决这个悖论?

解决方法:

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

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

但如果我添加完成:

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

……然后我明白了

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure “done()” is called; if returning a Promise, ensure it resolves.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐