Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock $http in AngularJS service Jasmine test?

I am trying to test an AngularJS service carService, but the $httpBackend does not seem to work.

//carService
angular.module('services').factory('carService',
    function($http) {
        return {
            getTypes: function() {
                return $http.get('/api/cars/types');
            }
        };
    });

Can anybody explain why the response is null?

describe("Services", function () {

    beforeEach(module("app.services"));

    describe("Car services", function () {

        var service, $httpBackend;

        beforeEach(inject(function($injector) {
            service = $injector.get('carService');
            $httpBackend = $injector.get('$httpBackend');

            $httpBackend.when('GET', "/api/cars/types").respond(["Toyota", "Honda", "Tesla"]);
        }));

        afterEach(function() {
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });

        it('getTypes - should return 3 car manufacturers', function () {
            service.getTypes().then(function(response) {
                expect(response.length).toEqual(3); //the response is null
            });
            $httpBackend.flush();
        });


    });
});
like image 575
Soni Ali Avatar asked Nov 03 '15 21:11

Soni Ali


People also ask

What service is used in jasmine for mocking http request?

You can definitely use spys to mock HTTP calls.

What is testing in AngularJS?

AngularJS testing is accomplished by utilizing the Karma framework, which was created by Google. The node package manager is used to install the Karma framework. For basic testing, the following important modules must be installed: karma, karma-chrome-launcher, karma-jasmine, and karma-cli.

What is Jasmine in AngularJS?

Jasmine is a behavior driven development framework for JavaScript that has become the most popular choice for testing AngularJS applications. Jasmine provides functions to help with structuring your tests and also making assertions.


1 Answers

Try this:

expect(response.data.length).toEqual(3);

The response object returned by a $http request has the response data within the data property (docs).

like image 95
sheilak Avatar answered Oct 27 '22 21:10

sheilak