Unit testing angular service with dependencies
I have the following Jasmine unit test:
describe('myService', function () {
var myService, $q;
// Instantiate the app
beforeEach(module('myApp'));
beforeEach(inject(function (_myService_, fileSystemService, $q) {
myService = _myService_;
spyOn(fileSystemService, 'listFiles').and.callFake(function () {
var deferred = $q.defer();
deferred.resolve('mockresult');
return deferred.promise;
});
}));
it('checks the number of outbound files', inject(function ($rootScope) {
var result;
myService.sendOutboundFiles2().then(function (res) {
result = res;
});
$rootScope.$digest();
expect(result).toBe('mockresult');
}));
});
Which tests this very simple service function:
sendOutboundFiles2() {
return fileSystemService.listFiles('Cached/Outbound').then(function(outfiles) {
return outfiles;
})
}
However when the test runs, it fails with a spurious Error: Unexpected request: GET blahblahblah.html No more request expected at $httpBackend
error but i have no idea why as neither this test nor the service dependencies do anything with $httpBackend.
MORE INFO
If i comment out my existing controller tests, I get this error:
If i add my controller tests back in, I get this error:
So depending on which tests i add or remove, the HTML file in the GET
error changes. But all the controller tests run fine. WTF?!?!?!!??!?!!?
The problem is caused by Ionic's keen prefetching of all templates into a cache. No idea why this doesn't occur when testing a controller though. The problem only appears when i was testing a service. Any way, I found this thread: Karma test breaks after using ui-router and the relevant fix is to add this snippets before injecting any dependencies:
beforeEach(module(function($provide) {
$provide.value('$ionicTemplateCache', function(){} );
}));
This stubs out the $ionicTemplateCache and prevents it from trying to preload all ui-router templates into the Ionic cache.
链接地址: http://www.djcxy.com/p/73390.html上一篇: 只有减号
下一篇: 单元测试依赖关系的角度服务