Search code examples
angularjsunit-testingjasminehttpbackend

How to get unit test working with $httpBackend?


I am just starting getting my head around unit testing and angular 1.2. I am using the $httpBackend service for testing a $httpcall in a service. This service is called inside my controller:

var app = angular.module('myApp', []);

app.controller('MainCtrl', function ( someService) {
    var vm = this;
    vm.hasError = false;

    //debugger;
    someService.someAsyncCall()
        .then(function (data) {
            vm.hasError = false;
        })
        .catch(function (data) {
            vm.hasError = true;
        });
});

app.factory('someService', function ($http) {
    return {
        someAsyncCall: function () {
            return $http.get("/data")
                .success(function (data) {
                    //return true
                })
                .error(function () {
                    console.log('error');
                    //return false
                });
        }
    };
});

I am trying to write a test for when the endpoint is wrong:

  beforeEach(function () {
        someServiceMock = jasmine.createSpyObj('someService', ['someAsyncCall']);
        module('myApp');

        inject(function ($rootScope, $controller, $q, _$timeout_,$httpBackend) {
            $scope = $rootScope.$new();
            someServiceMock.someAsyncCall.andReturn($q.when('weee'));
            $timeout = _$timeout_;
            controllerService = $controller;
            httpMock = $httpBackend;
        });
    });


    it("should set hasError=true with error request", function () {
        httpMock.expectGET("/datajfds").respond(false);
        ctrl = controllerService('MainCtrl', {someService: someServiceMock});
        expect(ctrl.hasError).toBe(true);
    });

This is the error:

MainCtrl testing should set hasError=true with error request.

Expected false to be true.
Error: Expected false to be true.
    at new jasmine.ExpectationResult (http://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.js:114:32)
    at .toBe (http://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.js:1235:29)
    at .<anonymous> (http://run.plnkr.co/Q77IyPb6agUqgR2U/specs.js:37:31)

Basically I would like to get coverage/write a test for when the someService.someAsyncCall() will catch an error. How can I write this test so that ctrl.hasError =true?

plunkr:http://plnkr.co/edit/aX29h4k64ZUm6hDedZl6?p=preview


Solution

  • There were lots of problems with what you were doing and I don't understand what you are trying to do with the third test. The api that you hit is configured in the service.

     $http.get("/data")
    

    See this plunker which might be that the tests that you were trying to do. Some problems:

    You were injecting a lot of things that weren't needed

    Your service call wasn't returning anything.

    You weren't getting the value from the service call