【问题标题】:mocha: how to call async functions in after()?mocha:如何在 after() 中调用异步函数?
【发布时间】:2014-05-07 01:10:33
【问题描述】:

我正在编写一个测试来验证模型的创建,然后在描述之后,它会释放所有资源。

我的问题是“done()”被多次调用,原因很明显,但我怎样才能实现这样的功能并且只调用一次呢?两个函数都是异步的!

测试结构和异步调用:

describe('create models', function() {
     it('...', function(done) {...});
});
after(function(done) {
         dbDestroyCenter('param1','param2')(done);
         dbDestroyCenter('param1','param2')(done);
});

删除功能:

function dbDestroyCenter(centerState, centerName) {
    return function (done) {
        State.findOne({ name: centerState }).exec(function (err, state) {

            if (err) return done(err);
            expect(state).not.to.be.an('undefined');

            Center.destroy({ state: state.id, name: centerName }).exec(function(err) {
                if (err) return done(err);
                return done();
            });
        });
    };
}

一种可能性是使用来自https://github.com/caolan/async 的 async.parallel,但我不确定 Mocha 是否为此提供解决方案。 有什么想法吗?

【问题讨论】:

  • 不,这就是 async 这样的东西的设计目的。 Mocha 不会复制该功能(它不需要)。您也可以将第二个 dbDestroyCenter 调用包装在一个函数中,并使 that 函数回调到第一个 dbDestroyCenter 而不是完成,但使用 async 更有效(也更漂亮)。

标签: mocha.js sails.js


【解决方案1】:

将您自己的回调传递给dbDestroyCenter 函数返回的函数并保持计数。一旦你被调用了你期望的次数,你就完成了,可以调用done

after(function(done) {
    // Initialize to the number of things to destroy.
    var to_destroy = 2;
    function destroyed(err) {
        // Terminate immediately if there's an error.
        if (err)
            done(err);

        // If there's nothing left to destroy, then call done().
        if (!--to_destroy)
            done();
    }

    dbDestroyCenter('param1','param2')(destroyed);
    dbDestroyCenter('param1','param2')(destroyed);
});

这是一般原则。

【讨论】:

  • 这确实是为您执行此操作的模块背后的一般原则,例如asyncstep。因此,虽然观看演示很有价值,但我不建议重新发明这个轮子!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 2020-12-20
  • 2014-02-08
  • 1970-01-01
相关资源
最近更新 更多