gpt4 book ai didi

javascript - 异步 Meteor.call 的 Mocha 测试

转载 作者:行者123 更新时间:2023-11-28 21:24:30 24 4
gpt4 key购买 nike

我是 Meteor 和 Mocha 的新手。看来我没有正确编写测试,我需要一些帮助。

基本上这就是我想要做的:

  1. 获取应用的状态
  2. 切换状态
  3. 再次获取当前状态
  4. 检查它是否被切换

.

if(Meteor.isServer) {
describe('should be able to toggle the status', function() {

// check if toggle working
it('should be able to toggle the status', function(done) {

// if app is in DB
if (Apps.findOne({ url: sampleUrl })) {

// get the current status
let status = Apps.findOne({ url: sampleUrl }).status;

// run toggle method
Meteor.call('toggle', Apps.findOne({ url: sampleUrl }), function(error) {

if (error) {
// handle error
console.log(error);
} else {

// get the current status again
const newStatus = Apps.findOne({ url: sampleUrl }).status;

// compare
expect(status).to.equal(!newStatus);
done();
}
});
}
});
});
}

问题是:

  1. 测试在 Meteor.call('toggle') 完成之前完成,如何让它等到 Meteor.call 完成后再继续测试?
  2. if (Apps.findOne({ url: sampleUrl })) 有时是假的,我认为这个 if 语句是在app还没有的时候调用的添加到数据库,如何确保应用程序已添加?我将应用程序添加为:

    // add app to DB before test
    before(function(done) {
    Meteor.call('addApp', app);
    done();
    });
  3. 除了 console.log(error) 之外,还有其他方法可以//handle error 吗?我希望 Mocha 抛出错误并说明错误并停止继续。

最佳答案

尝试下面的代码,如果不起作用请评论。我们可以做到这一点。

if (Meteor.isServer) {

// For Question 2: first call to your addApp
// addApp should return true, once the app is running
const isRunning = Meteor.call('addApp', app);
assert.isTrue(isRunning);

describe('should be able to toggle the status', function() {

// check if toggle working
it('should be able to toggle the status', function(done) {

// ensure that app is defined
// so no if required
const currentApp = Apps.findOne({ url: sampleUrl });
expect(currentApp ).to.notEqual(null);
expect(currentApp ).to.notEqual(undefined);

// get the current status from app
let status = currentApp.status;

// run toggle method
Meteor.call('toggle', Apps.findOne({ url: sampleUrl }), function(error) {

if (error) {
// Regarding question 3:
done(error);
} else {

// get the current status again
const newStatus = Apps.findOne({ url: sampleUrl }).status;

// compare
expect(status).to.equal(!newStatus);
done();
}
}); // close call
}); // close it
}); // close describe
}

关于问题 1,我只能说,在回调中使用 done 通常可以很好地让 mocha 等待您的 Meteor.call 完成。如果您按照问题 3 中的描述添加 done(error) 回调,也许它可以解决您的整体问题。

关于你的 meteor 法

通常你会模拟 addApp 方法的结果,例如使用 sinon 或手动确保此功能中的问题不会干扰您对 toggleApp 的测试。我真的建议你阅读更多关于模拟和 spy 的内容,以获得更干净和更独立的单元测试。

关于javascript - 异步 Meteor.call 的 Mocha 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43973833/

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