单元测试逻辑内部承诺回调 [英] Unit testing logic inside promise callback
问题描述
我有一个ES6 / Aurelia应用程序,我正在使用茉莉花进行测试。我试图测试的方法看起来像这样:
I have an ES6 / Aurelia app that I am using jasmine to test. The method I am trying to test looks something like this:
update() {
let vm = this;
vm.getData()
.then((response) => {
vm.processData(response);
});
}
其中 this.getData
是一个返回承诺的函数。
Where this.getData
is a function that returns a promise.
我的spec文件如下所示:
My spec file looks something like this:
describe('my service update function', () => {
it('it will call the other functions', () => {
myService = new MyService();
spyOn(myService, 'getData').and.callFake(function() {
return new Promise((resolve) => { resolve(); });
});
spyOn(myService, 'processData').and.callFake(function() { return; });
myService.update();
// this one passes
expect(myService.getData).toHaveBeenCalled();
// this one fails
expect(myService.processData).toHaveBeenCalled();
});
});
我理解为什么会失败 - 承诺是异步的,它在点击时尚未得到解决期待。
I understand why this fails - promises are asynchronous and it hasn't been resolved by the time it hits the expect.
如何从我的测试中推出解决方案,以便我可以测试回调中的代码?
How can I push the promises to resolve from my test so that I can test the code inside the call back?
失败测试的jsfiddle: http://jsfiddle.net/yammerade/2aap5u37/6/
jsfiddle of failed test: http://jsfiddle.net/yammerade/2aap5u37/6/
推荐答案
我通过返回一个行为类似于承诺而不是实际承诺的对象来运行变通方法
I got a workaround running by returning an object that behaves like a promise instead of an actual promise
describe('my service update function', () => {
it('it will call the other functions', () => {
myService = new MyService();
spyOn(myService, 'getData').and.returnValue({
then(callback) {
callback();
}
});
spyOn(myService, 'processData').and.callFake(function() { return; });
myService.update();
// this one passes
expect(myService.getData).toHaveBeenCalled();
// this one fails
expect(myService.processData).toHaveBeenCalled();
});
});
这里小提琴: http://jsfiddle.net/yammerade/9rLrzszm/2/
这样做是否有任何问题?
Is there anything wrong with doing it this way?
这篇关于单元测试逻辑内部承诺回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!