【发布时间】:2015-04-16 00:40:20
【问题描述】:
我正在使用 Mocha 为我的简单 Node.js 应用程序编写单元测试。该应用程序有一个类连接到 Mongo 数据库,获取记录,并将制定的记录存储为字段。简单地说,这个类看起来像这样:
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
});
});
}
从上面的 sn-p 可以看出,一旦调用了 SampleClass.init(),Sample.record 将不会立即从数据库中填充。一旦触发事件“打开”,数据就会异步填充。因此,在 SampleClass.init() 之后可能会有延迟,直到 Sample.record 被填充。
所以当我像这样编写摩卡测试时,它变得复杂了:
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 几秒钟或更长时间后启动?是否也可以在我的班级事件被触发后立即触发测试用例?否则,这个简单的案例总是会失败,我知道这根本不正确。
【问题讨论】:
标签: javascript node.js mongodb unit-testing mocha.js