Test Filters in AngularJS
- Estimated read time: 4 min read
- Written by Chad Campbell on Feb 1st 2014
One of AngularJS's core concepts are filters. Filters are used to prepare an expression's result for the user. In other words, to convert one value to another. This is useful for things like converting a boolean
false to a more user-friendly 'yes' or 'no'. In fact, that example will be used in this blog post to show how to test filters in AngularJS with Jasmine. You can view the demo or download the code.
Verify that the filter is loaded
In line #2 we are creating an instance of our filter. At this point in the game our only concern is that the filter is loaded. If you have a simple filter, now is the time to verify the filter works.
Verify the filter works
A lot of the time, you'll use a filter from your HTML markup. For instance,
MyFilter (which you can see in the code), converts
false to 'yes' and 'no'. An example of using this filter in HTML can be seen here:
MyFilter with Jasmine, you could use the following:
This example shows how to verify if a filter works. However, this example doesn't show how to test a filter that takes parameters.
Testing filters with parameters
When you're developing filters, your scenario may require the use of parameters. To pass parameters to a filter from the declarative HTML world, you could do something like the following:
This snippet shows the syntax of passing a parameter to a filter. If your filter required more parameters, you could append '
This past example doesn't show much new. In fact, the three tests written up to this point have been basic, even contrived. In reality, you only need to write the first test that we wrote. The past two tests have been provided to show you the syntax of writing tests. Either way, at some point you need to look at testing the business rules that your filter is shooting to meet.
testing your filter's business rules
When testing your business rules, its important to consider both expected and unexpected outcomes. For instance, here are two tests around the business rules that
MyFilter is attempting to meet.
The first test shows a test for an expected outcome. The second test shows a test for an unexpected outcome. The second test shows how to test for exceptions in Jasmine.
In review, first test that your filter is loaded. Once verified, you can turn your focus to the meat-and-potatoes of testing the business rules. This post showed you how to test filters in AngularJS. You can view the demo or download the code. If you found this post helpful, help the community, and share this post via Google Plus, LinkedIn, or Twitter. Thank you.