Filters in AngularJS help format data before displaying it in the UI. Testing filters ensures their correctness and reliability. Jasmine, a popular testing framework, provides a structured way to test AngularJS filters.
This guide covers:
- Setting up Jasmine for filter testing
- Writing unit tests for filters
- Handling different filter cases
- Best practices for testing filters
1. Setting Up Jasmine for Filter Testing
Jasmine is included in the Karma test runner, which is commonly used for AngularJS unit testing.
1.1 Install Required Packages
Ensure Jasmine, Karma, and necessary dependencies are installed:
npm install -g karma karma-jasmine karma-chrome-launcher jasmine-core karma-ng-html2js-preprocessor --save-dev
2. Writing and Testing a Custom AngularJS Filter
2.1 Creating a Custom Filter (app.js
)
Let’s create a simple filter that capitalizes the first letter of each word.
var app = angular.module('myApp', []);
app.filter('capitalize', function() {
return function(input) {
if (!input) return input;
return input.replace(/\b\w/g, function(char) {
return char.toUpperCase();
});
};
});
3. Writing Jasmine Unit Tests for Filters
3.1 Creating the Test File (capitalizeFilter.spec.js
)
describe('capitalize Filter', function() {
var capitalizeFilter;
// Load the module before each test
beforeEach(module('myApp'));
// Inject the filter before each test
beforeEach(inject(function($filter) {
capitalizeFilter = $filter('capitalize');
}));
it('should capitalize the first letter of each word', function() {
expect(capitalizeFilter('hello world')).toBe('Hello World');
expect(capitalizeFilter('angularjs testing')).toBe('Angularjs Testing');
});
it('should handle empty input gracefully', function() {
expect(capitalizeFilter('')).toBe('');
});
it('should return null if input is null', function() {
expect(capitalizeFilter(null)).toBe(null);
});
it('should return undefined if input is undefined', function() {
expect(capitalizeFilter(undefined)).toBe(undefined);
});
it('should not change already capitalized words', function() {
expect(capitalizeFilter('Hello World')).toBe('Hello World');
});
it('should handle mixed case words correctly', function() {
expect(capitalizeFilter('aNgularJS iS aweSome')).toBe('ANgularJS IS AweSome');
});
});
4. Running the Tests
Modify karma.conf.js
to include the test files:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'angular.min.js',
'angular-mocks.js',
'app.js',
'tests/capitalizeFilter.spec.js'
],
browsers: ['Chrome'],
singleRun: true
});
};
Run the tests using:
karma start
5. Best Practices for Testing Filters
✔ Test edge cases (empty strings, null, undefined, numbers).
✔ Use beforeEach(module('myApp'))
to load the AngularJS app.
✔ Use beforeEach(inject())
to get the filter instance.
✔ Test performance for large input cases.
✔ Ensure filters don’t modify original input (return new values).