punkbit punkbit - 1 year ago 96
AngularJS Question

angularjs 1 and jasmine, service promise testing

I'm trying to figure out how to test a service promise using karma + jasmine but without success. So far this is what I did with the result errors:

PhantomJS 2.1.1 (Mac OS X 0.0.0) The FetchData service should fetch data FAILED
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

fetchData service:

module.exports = function($http) {
return {
getFoo: function(id) {
return $http.get('https://api/' + id)
.then(function(result) {
return result.data;


describe('The FetchData service', function() {

var dataFetcher;


beforeEach(inject(function(_dataFetcher_) {
dataFetcher = _dataFetcher_;

it('should fetch data', function(done) {

var testData = function(res) {

var failTest = function(error) {



I wonder if there's something that I might be missing that can help me understand this,


Answer Source

You need to inject the $httpBackend service in your tests to mock the $http service.

Then you need to call $httpBackend.flush to mock the actual HTTP call. Please check the angular docs for example.


it('should fetch data', function () {

  var status, data;
  function successCB(response){
     status = 'success';
     data = response.data;
  function errorCB(){
     status = 'error'
  //only pass the success and error callbacks here
  dataFetcher.get(1).then(successCB, errorCB);

  // you need to stop it    

  //assert for success
     .when('GET', 'https://api/1')
     .respond(200, {foo:'bar'});

  expect(data).toEqual({foo: 'bar'});

  //assert for error
     .when('GET', 'https://api/1')
     .respond(500, 'An error has occured.');


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download