Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing AngularJS route with "resolve"

I am trying to unit test one of my routes and I get the infamous "Error: Unexpected request" error. My route takes in a "resolve" parameter and looks like this:

when('/Users',
                {
                    templateUrl: 'app/users/user-list.tpl.html',
                    controller: 'UserListCtrl',
                    resolve: {
                        userAccounts: ['UserAccounts', function(UserAccounts) {
                            return UserAccounts.query({ id: 123 });
                        }]
                    }
                })

where UserAccounts is a "resource". I am testing my route as follows:

beforeEach(inject(function (_$route_, _$location_, _$rootScope_, _$httpBackend_) {
        $route = _$route_;
        $location = _$location_;
        $rootScope = _$rootScope_;
        $httpBackend = _$httpBackend_;

        $httpBackend.when('GET', 'api/Accounts/123/UserAccounts').respond([]);
        $httpBackend.when('GET', 'app/users/user-list.tpl.html').respond({});
    }));

it('/Users should get user-list template and use UserListCtrl', inject(function($controller) {
            $httpBackend.expectGET('app/users/user-list.tpl.html');
            $httpBackend.expectGET('api/Accounts/123/UserAccounts');

            expect($route.current).toBeUndefined();
            $location.path('/Users');
            $rootScope.$digest();

            expect($route.current.loadedTemplateUrl).toBe('app/users/user-list.tpl.html');
            expect($route.current.controller).toBe('UserListCtrl');
    }));

And the test fails with Error: Unexpected request: GET http://myserver/api/Accounts/123/UserAccounts. This is the get that my resolve is calling. Any ideas what the right way is to test such a route?

like image 660
mithun_daa Avatar asked Feb 04 '14 19:02

mithun_daa


1 Answers

Two things look strange about your test code.

First, your beforeEach method has the GET requests duplicated with those being called in the actual test. Try removing them.

Second, it looks as if you are missing a call to $httpBacken.flush() before your final assertions.

Hopefully this helps.

like image 82
Coding Smackdown Avatar answered Sep 28 '22 08:09

Coding Smackdown