Ash*_*osh 5 mocha.js node.js promise
我正在 Nodejs 中使用 mocha 编写测试用例,并希望在运行测试之前重置数据库数据。我使用 Knex 作为查询生成器来执行查询。
我写了以下逻辑:
describe('Activities:', function() {
before(funtion(){
activityDBOperations.deleteAll()
.then(function(){
// all records are deleted
});
});
it('it should add a record into Activities table: multiple time activity', function(done) {
activityDBOperations.addRecord(requestParams)
.then(function(data) {
expect(data.length > 0).to.equal(true);
done();
});
});
});
Run Code Online (Sandbox Code Playgroud)
问题是测试用例开始执行而不是等待deleteAll 操作完成。我的理解是,由于deleteAll正在返回promise,因此由于promise的异步性质,程序执行会向前推进。
如何确保测试用例仅在 deleteAll 完成后运行?
要么为您的钩子提供回调before并在以下位置调用它then:
before(function(done) {
activityDBOperations.deleteAll()
.then(function() {
// all records are deleted
done();
});
});
Run Code Online (Sandbox Code Playgroud)
或者,根据Mocha 文档,只需返回一个承诺before:
before(function() {
return activityDBOperations.deleteAll();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4701 次 |
| 最近记录: |