如果我有这样的服务和过滤器:
angular.module('myApp', [])
.filter('myFilter', [function() {
return function() { return 1; };
}])
.service('myServiceWhichCallsMyFilter', ['$filter', function($filter) {
this.callTheFilter = $filter('myFilter');
}]);
和这样的测试:
describe('myFilterTest', function() {
var $filter;
beforeEach(module('myApp'));
beforeEach(inject(function (_$filter_) {
$filter = _$filter_;
}));
it('should filter correctly', function() {
var filteredValue = $filter('myFilter')(100);
expect(filteredValue).to.equal(1); // passes
});
});
describe('myServiceTest', function() {
var myServiceWhichCallsMyFilter;
var myFilterSpy = sinon.spy();
beforeEach(module('myApp'));
beforeEach(module(function ($provide) {
$provide.value('myFilter', myFilterSpy);
}));
beforeEach(inject(function (_myServiceWhichCallsMyFilter_) {
myServiceWhichCallsMyFilter = _myServiceWhichCallsMyFilter_;
}));
it('should call myFilter', function() {
myServiceWhichCallsMyFilter.callTheFilter();
expect(myFilterSpy.callCount).to.equal(1); // fails - callCount is 0
});
});
......我怎样才能通过第二次测试?在该测试中,我只对服务是否调用过滤器感兴趣(不是过滤器的正确性,我单独测试),所以我想模仿它。但$provide.value('myFilter', myFilterSpy)
似乎不起作用。
答案 0 :(得分:0)
angular.module('myApp', [])
.filter('myFilter', [function() {
return function() { return 1; };
}])
.service('myServiceWhichCallsMyFilter', ['$filter', function($filter) {
this.callTheFilter = $filter('myFilter');
}]);
请注意,您的服务实际上并未调用$ filter,而只是实例化它。
如下所示更改该行,您的测试将“通过”,尽管您正在改变行为,因此...找出您想要它做什么
this.callTheFilter = $filter('myFilter')(100);
答案 1 :(得分:0)
知道了:在第二次测试中,我需要$provide
我的间谍过滤器,名称为myFilterFilter
:
describe('myServiceTest', function() {
var myServiceWhichCallsMyFilter;
var myFilterSpy = sinon.spy();
beforeEach(module('myApp'));
beforeEach(module(function ($provide) {
$provide.value('myFilterFilter', myFilterSpy );
}));
beforeEach(inject(function (_myServiceWhichCallsMyFilter_) {
myServiceWhichCallsMyFilter = _myServiceWhichCallsMyFilter_;
}));
it('should call myFilter', function() {
expect(myFilterSpy.callCount).to.equal(0); // callTheFilter has not been called!
myServiceWhichCallsMyFilter.callTheFilter();
expect(myFilterSpy.callCount).to.equal(1); // passes
});
});
实际上在文档中提到了这一点:"Notice that the suffix 'Filter' is appended to your filter name when injected"。