我是 Meteor 和 Mocha 的新手。看来我没有正确编写测试,我需要一些帮助。
基本上这就是我想要做的:
- 获取应用的状态
- 切换状态
- 再次获取当前状态
- 检查它是否被切换
.
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();
}
});
}
});
});
}
问题是:
- 测试在
Meteor.call('toggle')
完成之前完成,如何让它等到 Meteor.call 完成后再继续测试? if (Apps.findOne({ url: sampleUrl }))
有时是假的,我认为这个if
语句是在app还没有的时候调用的添加到数据库,如何确保应用程序已添加?我将应用程序添加为:// add app to DB before test before(function(done) { Meteor.call('addApp', app); done(); });
除了
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/