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

Leave a Comment