gpt4 book ai didi

node.js - Mocha 测试用例不等待完成

转载 作者:行者123 更新时间:2023-12-04 03:14:57 24 4
gpt4 key购买 nike

我正在 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();
});
});
});

问题是测试用例开始执行而不是等待 deleteAll 操作完成。我的理解是,由于 deleteAll 正在返回 promise ,程序执行由于 promise 的异步性质而向前推进。

如何确保仅在 deleteAll 完成时才运行测试用例?

最佳答案

要么向您的 before 提供回电 Hook 并在 then 中调用它:

before(function(done) {
activityDBOperations.deleteAll()
.then(function() {
// all records are deleted
done();
});
});

或者,根据 Mocha docs , 只需返回来自 before 的 promise :
before(function() {
return activityDBOperations.deleteAll();
});

关于node.js - Mocha 测试用例不等待完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41934286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com