Mocha 异步测试,调用 done() 问题

Mocha async tests, calling done() issue

我正在开发 postcss 插件并想用 mocha 测试它。 这是我的测试:

function exec(cb) {
    postcss()
        .use(regexp)
        .process(source)
        .then(cb);
}

it('should add warnings to messages', function(done) {
    var expected = 'somemessage';
    var message = '';

    function getMessage(result) {
        message = result.messages;
        assert.equal(message, expected);
        done();
    }

    exec(getMessage);
});

但是它失败了,我得到 Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test

我做错了什么?

您的回调未在 2000 毫秒的默认超时内被调用。

如果您确定您的 exec 插件没有任何问题并且预计需要超过 2 秒,您可以使用

增加时间

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded.

我自己找到了解决办法!我们需要 return 在 execit 中做出承诺,因此在 done()

中就没有必要了
function exec(cb) {
    return postcss()
        .use(regexp)
        .process(source)
        .then(cb);
}

it('should add warnings to messages', function() {
    var expected = 'somemessage';
    var message = '';

    function getMessage(result) {
        message = result.messages;
        assert.equal(message, expected);
    }

    return exec(getMessage);
});