How to unit test a filter in AngularJS 1.x

eddiec picture eddiec · Jan 13, 2014 · Viewed 33.8k times · Source

How do you unit test a filter in Angular?

Answer

eddiec picture eddiec · Jan 13, 2014

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