Unit Test AngularJS Controller API Callback With Jasmine

I started looking into Angular unit testing with Jasmine a few weeks back. There were a ton of great articles to help you get started with setting up a basic unit test that tested against a controller. What I had a hard time finding though, was one that showed how to test mock data for an API callback. So that is what i’ll be covering with this post.

I started by creating a beforeEach function. This simplifies the actual test as you won’t have to inject these modules each time.

The code above simply injects the necessary modules before each test. Including the three important ones for unit testing a controller with an API call: $rootScope, $controller, and $httpBackend.

Here is the actual test for my controller:

The three lines to note are the httpBackend lines.

The expectGet needs to be set if you are setting scope for an html page.

The whenGet is what mocks up the data that is returned from the API call.

I had those 2 functions set and still couldn’t get back the results I expected.

The key was the httpBackend.flush() line. This method flushes out the response you provided in your test.

Here is the source project on GitHub: https://github.com/allensb/StudentManagement