在角测试抖功能,茉莉从未调用函数 [英] Testing a debounced function in Angular with Jasmine never calls the function
问题描述
我在使用下划线的去抖服务的方法。
I have a method in a service that uses underscore's debounce.
内该方法是在一个不同的服务的方法的调用。我想测试不同的服务被调用。
Inside that method is a call to a method on a different service. I'm trying to test that the different service is called.
在我尝试测试方法去抖,不同的服务'的方法不会被调用,和茉莉失败:
In my attempts to test the debounced method, the different services' method is never called, and jasmine fails with:
间谍预计到amethod方法被调用。
"Expected spy aMethod to have been called."
我知道一个事实,这就是所谓的(它会在Chrome浏览器控制台),它只是调用后预期已经失败。
I know for a fact that it IS called (it logs to console in chrome), it's just called AFTER the expectation already failed.
所以...(pferably $ P $)无需添加兴农或其他依赖和结果
奖励分*给予的溶液不必转动_.debounce成$超时...
So... (preferably) without adding Sinon or another dependency and with
bonus points* given to a solution doesn't have to turn the _.debounce into a $timeout...
怎么办?
angular.module('derp', [])
.service('herp', function(){
return {
aMethod: function(){
console.log('called!');
return 'blown';
}
};
})
.service('Whoa', ['herp', function(herp){
function Whoa(){
var that = this;
this.mindStatus = 'meh';
this.getMind = _.debounce(function(){
that.mindStatus = herp.aMethod();
}, 300);
}
return Whoa;
}]);
测试:
describe('Whoa', function(){
var $injector, whoa, herp;
beforeEach(function(){
module('derp');
inject(function(_$injector_){
var Whoa;
$injector = _$injector_;
Whoa = $injector.get('Whoa');
herp = $injector.get('herp');
whoa = new Whoa();
});
});
beforeEach(function(){
spyOn(herp, 'aMethod').andCallThrough();
});
it('has a method getMind, that calls herp.aMethod', function(){
whoa.getMind();
expect(herp.aMethod).toHaveBeenCalled();
});
});
为什么有角测试神离弃我?
Why have the Angular Testing gods forsaken me?
*我不知道怎么给计算器上实际的加分,但如果可能的话,我会的。
* I do not know how to give actual bonus points on stackoverflow, but if it is possible, i will.
推荐答案
您只需要模拟lodash去抖方法:
You just need to mock lodash debounce method:
describe('Whoa', function(){
var $injector, whoa, herp;
beforeEach(function(){
module('derp');
spyOn(_, 'debounce').andCallFake(function(cb) { return function() { cb(); } });
inject(function(_$injector_){
var Whoa;
$injector = _$injector_;
Whoa = $injector.get('Whoa');
herp = $injector.get('herp');
whoa = new Whoa();
});
});
beforeEach(function(){
spyOn(herp, 'aMethod').andCallThrough();
});
it('has a method getMind, that calls herp.aMethod', function(){
whoa.getMind();
expect(herp.aMethod).toHaveBeenCalled();
});
});
这篇关于在角测试抖功能,茉莉从未调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!