Search code examples
angularjsjasminetddhttpbackend

Calling a method from an injected service in Jasmine


I'm attempted to unit test a service. I've injected the service however the method call getAllProducts() doesn't appear to run however the test still passes!

Plnkr

service.js

angular.module('vsApp')
  .factory('productsDataService', function($http) {

    var service = {

      getAllProducts: getAllProducts

    };

    // get all products

    function getAllProducts() {

      return $http.get('/apiv1/getAllProducts/').then(function(data) {

        return (data);

      });

    }

    return service;
  });

spec.js

// jasmine

describe('products data service', function () {

    var $httpBackend, productsDataService;

    beforeEach(module('vsApp'));

    beforeEach(inject(function(_$httpBackend_, _productsDataService_) {

        $httpBackend = _$httpBackend_;
        productsDataService = _productsDataService_;

    }));

    it('should get all products', inject(function() {
        console.info("get all");
        // mock response for the http call in the service

        $httpBackend.when('GET', '/apiv1/getAllProducts/')
            .respond({name: 'item', price: '932'});

        //this doesn't seem to run??
        productsDataService.getAllProducts().then(function(response) {
            expect(response.data.length).toBeGreaterThan(1);

        });

    }));

});

Solution

  • Ok, you have to make it sync. (all pending request will get resolved) using $http.flush();

    Working demo as expected

    productsDataService.getAllProducts().then(function(response) {
        console.log(response);
        expect(response.data.length).toBeGreaterThan(999);
    
    });
    
    $httpBackend.flush(); // <=============== here.