How to unit test a filter in AngularJS 1.x
Inject $filter
and then call it with $filter('filterName')(input, options);
So to test the equivalent of this template {{ foo | testFilter:capitalize }}
describe('The test filter', function () {
'use strict';
var $filter;
beforeEach(function () {
module('myTestFilterModule');
inject(function (_$filter_) {
$filter = _$filter_;
});
});
it('should capitalize a string', function () {
// Arrange.
var foo = 'hello world', result;
// Act.
result = $filter('testFilter')(foo, 'capitalize');
// Assert.
expect(result).toEqual('HELLO WORLD');
});
});
You can inject $filter and load the filter that you want to test. Then you pass the parameter to be filtered through the filter you have injected and you 'expect' what you needed. Here is an example:
describe('Filter test', function(){
var filter;
beforeEach(function(){
module.apply(moduleName);
inject(function($injector){
filter = $injector.get('$filter')('nameOfTheFilter');
});
});
it('should filter the parameters passed', function(){
expect(filter(parameterToBeFiltered)).toBe(Result);
});
});