我们的项目中有很多代码由于 ember 并发任务而未涵盖。
是否有一种简单的方法来对包含以下内容的 Controller 进行单元测试:
export default Controller.extend({
updateProject: task(function* () {
this.model.project.set('title', this.newTitle);
try {
yield this.model.project.save();
this.growl.success('success');
} catch (error) {
this.growl.alert(error.message);
}
})
});```
最佳答案
您可以通过调用 someTask.perform()
来对这样的任务进行单元测试。对于给定的任务,您可以 stub 您需要的内容,以便彻底测试它:
test('update project task sets the project title and calls save', function(assert) {
const model = {
project: {
set: this.spy(),
save: this.spy()
}
};
const growl = {
success: this.spy()
};
// using new syntax
const controller = this.owner.factoryFor('controller:someController').create({ model, growl, newTitle: 'someTitle' });
controller.updateProject.perform();
assert.ok(model.project.set.calledWith('someTitle'), 'set project title');
assert.ok(growl.success.calledWith('success'), 'called growl.success()');
});
这是使用来自 sinon 的 spy 和 ember-sinon-qunit从测试上下文访问 sinon,但这些对于单元测试来说不是必需的。您可以使用断言而不是 spy 来对模型和服务等进行 stub :
const model = {
project: {
set: (title) => {
assert.equal(title, 'someTitle', 'set project title');
},
save: () => {
assert.ok(1, 'saved project');
}
}
};
要测试捕获,您可以从 stub model.project.save()
方法中抛出:
const model = {
project: {
...
save: () => throw new Error("go to catch!")
}
};
关于javascript - 对 ember 并发任务和产量进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58452244/