[英]Unit testing ember-concurrency tasks and yields
由於 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()
對這樣的任務進行單元測試。 對於給定的任務,您可以存根您需要的內容以徹底測試它:
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和ember-sinon-qunit的間諜從測試上下文訪問 sinon,但這些對於單元測試不是必需的。 您可以使用斷言而不是間諜來存根 model 和服務等:
const model = {
project: {
set: (title) => {
assert.equal(title, 'someTitle', 'set project title');
},
save: () => {
assert.ok(1, 'saved project');
}
}
};
要測試捕獲,您可以從您的存根model.project.save()
方法中拋出:
const model = {
project: {
...
save: () => throw new Error("go to catch!")
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.