如何在开始摩卡测试用例之前添加延迟?

How to add a delay before starting a Mocha test case?

我正在使用 Mocha 为我的简单 Node.js 应用程序编写单元测试。该应用程序有一个 class 连接到 Mongo 数据库,获取记录,并将制定的记录存储为字段。简单地说,class 看起来像这样:

SampleClass.prototype.record = []; // Store the loaded record
SampleClass.prototype.init = function(db){
    var self = this;
    self.db = mongoose.connection; // Say we already have mongoose object initialized
    self.db.once('open',function(){
        /* schema & model definitions go here */
        var DataModel = mongoose.model( /* foobar */);
        DataModel.findOne(function(err,record){
           /* error handling goes here */ 

           self.record = record; // Here we fetch & store the data
        });
    });
}

从上面的代码片段可以看出,一旦 SampleClass.init() 被调用,Sample.record不会立即从数据库中填充。触发事件 'open' 后,数据将异步填充。因此,在 SampleClass.init() 之后可能会有延迟,直到填充 Sample.record

所以当我像这样编写 Mocha 测试时,它就变得复杂了:

var testSampleClass = new SampleClass();

describe('SampleClass init test',function(){
    testSampleClass.init('mydb');
    it('should have 1 record read from mydb',function(){
        assert.equal(testSampleClass.record.length,1);
    });
});

上面的断言总是会失败,因为 testSampleClass.record 不会在 init 之后立即填充。加载数据需要一定的时间间隔

如何延迟测试用例,使其在调用 testSampleClass.init 几秒或更长时间后开始?是否也可以在触发我的 class 事件后立即触发测试用例?否则,这个简单的案例总是会失败,我知道这根本不正确。

使用 before()beforeEach 挂钩(参见 here and here)。它们以 done 回调为参数,当一些异步工作人员将完成时,您必须调用它。所以你的测试应该是这样的:

describe('SampleClass init test',function(){
    before(function(done) {
        testSampleClass.init('mydb', done);
    });
    it('should have 1 record read from mydb',function(){
        assert.equal(testSampleClass.record.length,1);
    });
});

还有你的初始化方法:

SampleClass.prototype.record = []; // Store the loaded record
SampleClass.prototype.init = function(db, callback){
    var self = this;
    self.db = mongoose.connection; // Say we already have mongoose object initialized
    self.db.once('open',function(){
        /* schema & model definitions go here */
        var DataModel = mongoose.model( /* foobar */);
        DataModel.findOne(function(err,record){
            /* error handling goes here */

            self.record = record; // Here we fetch & store the data
            callback();
        });
    });
}

@alexpods 提出了一个很好的建议。将以下内容添加到您的测试集合中,以便每个测试步骤在 运行.

之前等待 500 毫秒
  beforeEach(function (done) {
    setTimeout(function(){
      done();
    }, 500);
  });

或在 ES6 中

 beforeEach(done => setTimeout(done, 500));

感谢@Timmerz 的建议