Skip to content

learn-co-students/angular-testing-custom-filters-readme-dc-web-120919

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Testing custom Filters

Overview

Now that we've created a custom filter, it's important that we test the output of the filter to make sure it's doing its job properly.

Objectives

  • Describe testing filters
  • Write a custom filter unit test

Testing filters

Like our services, we can inject filters into our tests. We use the $filter helper.

As our filters do not care explicitly what type of data is given to them, we don't need to load them up in Protractor and test them in the actual application. We can simply inject them into our karma tests and test the functionality out of them with any data!

Let's say we've got this filter:

function firstUppercase() {
	return function (str) {
		return str.charAt(0).toUpperCase() + str.slice(1);
	};
}

angular
	.module('app')
	.filter('firstUppercase', firstUppercase);

We can inject this using $filter in our tests:

describe('UserService', function () {
	var $controller, firstUppercase;

	beforeEach(module('app'));

	beforeEach(inject(function ($filter) {
		firstUppercase = $filter('firstUppercase');
	}));
});

Now, as we returned a function in our filter, we can simply call firstUppercase as a function and receive our manipulated value in return.

describe('UserService', function () {
	var $controller, firstUppercase;

	beforeEach(module('app'));

	beforeEach(inject(function ($filter) {
		firstUppercase = $filter('firstUppercase');
	}));

	it('should capitalise the first letter', function () {
		expect(firstUppercase('test')).toEqual('Test');
	});
});

Nice - our tests now pass! You can pass through any data you like, meaning we can also test any filters that we create on datasets.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published