IAmAkittycatAMA IAmAkittycatAMA - 5 months ago 9
Javascript Question

How to test $http with Jasmine in AngularJS

I'm trying to test the data received from an $http request in my controller.

I don't have too much experience testing with Angular so I'm struggling to under stand how to do it.

$scope. always comes back undefined and when I've tried fetching the data from the test, that seems to fail also. What am I missing?

Controller:

'use strict';

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

myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}]);


myApp.controller('View1Ctrl', [

'$scope',
'$http',

function($scope, $http) {
$http.get('view1/data.json')
.then(function(res){
$scope.data = res.data.data
});
}]);


Test:

'use strict';

describe('myApp.view1 module', function() {

beforeEach(module('myApp.view1'));


describe('view1 controller', function(){

var scope, testCont;

beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
testCont = $controller('View1Ctrl', {$scope: scope});
}));

it('should....', function(){
expect($scope.data).toBeDefined();
});

});
});

Answer

The HTTP requests will not fire unless you call $httpBackend.flush().

More information can be found here: http://docs.angularjs.org/api/ngMock.$httpBackend

Test:

'use strict';

describe('myApp.view1 module', function() {
var $httpBackend, $rootScope, createController, jsonHandler;
beforeEach(module('myApp.view1'));


describe('view1 controller', function(){

var scope, testCont;

  beforeEach(inject(function($rootScope, $controller, $injector) {
   // Set up the mock http service responses
   $httpBackend = $injector.get('$httpBackend');
   // backend definition common for all tests
   jsonHandler= $httpBackend.when('GET', '/view1/data.json')
                            .respond({data: '[XXX,XXX,XXX]'});
    // Get hold of a scope (i.e. the root scope)
    $rootScope = $injector.get('$rootScope');
    // The $controller service is used to create instances of controllers
    var $controller = $injector.get('$controller');

    createController = function() {
        return $controller('View1Ctrl', {'$scope' : $rootScope });
    };

  }));

it('should....', function(){

   $httpBackend.expectGET('/view1/data.json');
   var controller = createController();
    $httpBackend.flush();
});

});
});
Comments