我想测试一个AngularJS自定义过滤器,它对它有另一个过滤器依赖。我怎么能做到这一点?
我的过滤器如下所示:
angular.module('myApp')
.filter('addressLocations', function($filter) {
return function(input, startFromIndex) {
var arr = angular.copy(input);
if (startFromIndex) {
arr = arr.splice(startFromIndex);
}
var locations = '';
angular.forEach(arr, function(address) {
locations += $filter('location')(address) + '<br>';
});
return locations;
};
});
我的Jasmine测试看起来就像那样:
describe('addressLocations', function () {
var filter;
beforeEach(module('myApp'));
beforeEach(inject(function(addressLocations) {
// ??? how to inject $filter into `addressLocations` ???
filter = addressLocations;
}));
it('should filter correctly', function() {
var input = [{
city: 'Karlsruhe',
country: 'Germany'
}, {
city: 'Berlin',
country: 'Germany'
}, {
city: 'Stuttgart',
country: 'Germany'
}, {
city: '',
country: 'Germany'
}, {
city: '',
country: ''
}];
expect( filter(input, 1) ).toEqual('Berlin, Germany<br>Stuttgart, Germany<br>Germany<br>Unknown');
});
});
我知道上面的代码更像是一个集成测试,但如果我知道如何在过滤器中注入依赖项,我会注入一个模拟函数来测试单元,而不是依赖它。
提前致谢!
答案 0 :(得分:-1)
我不明白你的问题,但要测试过滤器,你应该注入$ filter而不是addressLocations
var filter;
beforeEach(module('myApp'));
beforeEach(inject(function(_$filter_) {
filter = _$filter_;
}));
...
expect( filter('addressLocations')(input, 1) )..