Until recently, the front-end testing I’d done had not directly tested any Angular services. In almost every case, the $http calls in the services were just returning data from an API back to a controller. However, on a recent project I had a scenario where the data from the API had to have some filtering and permission logic applied before passing on the data. This was a case where unit testing the service made sense.
As it turns out, testing a service is very similar to testing a controller in terms of setting up the test, injecting dependencies, and making assertions. The only real difference is the need to mock the $http call in the service. To do this the angular-mocks library provides the $httpBackend tool. Let’s walk through an example of testing a service.
I was writing some tests for an Angular app and ran into a scenario where I needed a page to behave differently if the time of day was before or after 6AM. The logic is simple enough to capture in my controller:
vm.date = moment().subtract(6, 'hours').toDate();
Basically, if it is before 6AM, display the prior day, otherwise display today. However, as I was trying to write a test for this controller the problem came up: how do I take control of the current time to test both scenarios?
Note: If you have interest in checking out the project, you can find it here:
If you’re not familiar with CodeMash, it’s a technology conference hosted at the Kalahari Resort & Indoor Water Park in Sandusky, OH:
CodeMash is a unique event that will educate developers on current practices, methodologies, and technology trends in a variety of platforms and development languages such as Java, .NET, Ruby, Python and PHP.