I am trying to test a real http call with Jasmine (integration test), but when i call a method that uses $http.get, it times out and the server never gets called.
I know that I am supposed to inject the implementation of $http but not sure where that should happen.
searchSvc
app.service('searchSvc', ['$http', '$q', searchSvc]);
function searchSvc($http, $q) {
return {
search: function(text) {
console.log('svc.search called with ', text); // this does get called
return $q.when($http.get('/search/' + text));
}
};
}
searchSpec
describe("searchTest", function() {
var ctrl, svc, $http;
beforeEach(function () {
module('testApp');
inject(function(_$controller_, searchSvc, _$http_){
ctrl = _$controller_('searchCtrl');
svc = searchSvc;
$http = _$http_;
})
});
it('test server search', function(done) {
svc.search('re').then(function(result) {
console.log('promise then'); // this never gets called, because server never gets called
expect(result).not.toBeNull();
expect(result.data).not.toBeNull();
expect(result.data.length).toBeGreaterThan(0);
done();
});
});
This is sort of hypothetical, but if you include both
ngMock
&ngMockE2E
modules as your app module's dependency (ngMock
needs to come beforengMockE2E
in the dependency list) you should be able to use$httpBackend
service provided byngMockE2E
module topassThrough
the search api call to actual backend in your test specs.Try something like this and see whether it works:
In case if you use promises you can find out how to deal with them here http://entwicklertagebuch.com/blog/2013/10/how-to-handle-angularjs-promises-in-jasmine-unit-tests/
Here is a solution that I use to make real HTTP calls when I'm using ngMock for unit tests. I mainly use it for debugging, working through the test, getting JSON examples etc.
I wrote a more detailed post about the solution on my blog: How to Unit Test with real HTTP calls using ngMockE2E & passThrough.
The solution is as follows:
Include this source file after ngMock, for example:
How to write the test?
How it works?
It uses ngMockE2E's version of $httpBackEndProvider, which provides us with the passThrough function we see being used in the test. This does as the name suggests and lets a native HTTP call pass through.
We need to re-define the ngMock module without its fake version of the $BrowserProvider, since that is what prevents the real HTTP calls in unit tests that use ngMock.