How to unit test a filter in AngularJS 1.x How to unit test a filter in AngularJS 1.x angularjs angularjs

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);  });});


Filter can be injected right into test (have found a snippet here)

  describe('myApp', function () {    beforeEach(function () {      module('myApp');    });    it('has a bool filter', inject(function($filter) {      expect($filter('bool')).not.toBeNull();    }));    it("should return true empty array ", inject(function (boolFilter) {      expect(boolFilter(true)).toBeTruthy();    }));  });

In this example filter name is 'bool', in order to inject this filter you shall use 'bool' + 'Filter' = 'boolFilter'