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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With