How do you unit test a filter in Angular?
Load the Angular App beforeEach(module('MyApp')); //3. Describe the object by name describe('compute', function () { var compute; //4. Initialize the filter beforeEach(inject(function ($filter) { compute = $filter('compute', {}); })); //5. Write the test in the it block along with expectations.
AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.
In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.
The “filter” Filter in AngularJS is used to filter the array and object elements and return the filtered items. In other words, this filter selects a subset (a smaller array containing elements that meet the filter criteria) of an array from the original array.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With