I'm using Angular with Angular UI's router. As part of the router configuration, I have a resolve
that runs through a few API calls:
$stateProvider.state('someState', {
templateUrl: '...',
resolve: {
auth: someFunction
},
controller: 'SomeStateCtrl'
});
someFunction()
will do an API call: GET /someAPICall
.
Now, say I'm writing a test for some service that has absolutely nothing to do with this state, someFunction()
, or GET /someAPICall
:
angular.module('app').service('SomeSvc', function () {
this.something = function () {
return $http.get('/someOtherCall');
};
});
describe('SomeSvc Test', function () {
var SomeSvc, $httpBackend;
beforeEach(module('app'));
beforeEach(inject(function (_SomeSvc_, _$httpBackend_) {
SomeSvc = _SomeSvc_;
$httpBackend = _$httpBackend_;
}));
it('test', function () {
$httpBackend.whenGET('/someOtherCall').respond({
example: 'text'
});
SomeSvc.something().then(function (data) {
expect(data.example).toBe('text');
});
$httpBackend.flush();
});
});
As seen above, SomeSvc
makes a call to /someOtherCall
, but NOT /someAPICall
. But when I go to run this unit test, the $httpBackend.flush()
ends up trying to process /someAPICall
that was spawned from the router:
Error: Unexpected request: GET /someAPICall
Of course I can easily fix this by providing an extra .whenGET
in my test to handle /someAPICall
, but this doesn't scale. My initial thought was to create some sort of global testing service that handles all of these router API calls (there are more than in my simplified example), so I don't need to redefine them in any of my tests. However, given that I can't seem to find any information on the matter, I feel like something I'm doing is missing the mark and I should be running this a different way.
Any input is appreciated.
.whenGET
.