mardi 6 janvier 2015

Mocking service containing http request for unit testing in angular

I got a controller like that:



.controller('MainCtrl', function ($scope, API) {
$scope.eventsQuantity = 0;
$scope.localsQunatity = 0;

API.newRequest('getCitiesList').success(function (data) {
$scope.cities = data.data;
for (var i = 0; i < $scope.cities.length; i++) {
$scope.eventsQuantity += parseInt($scope.cities[i].EventCount);
$scope.localsQunatity += parseInt($scope.cities[i].LocalCount);
}
});


})


which is using API service with http request:



angular.module('sandboxApp').factory('API', function ($http) {
return {
'newRequest': function (path, conf) {
return $http.get('http://ift.tt/1tGnrLm' + path, conf);
},
'baseURL': 'http://ift.tt/1tGnrLm'
};


})


how can i mock this service when im writing unit test for my controller so i dont have to send real http request during testing ? I have tried something like this:



describe('Controller: MainCtrl', function () {

// load the controller's module
beforeEach(module('sandboxApp'));

var MainCtrl, scope, mockAPI;

beforeEach(function () {
var mockAPI = {};
module('sandboxApp', function ($provide) {
$provide.value('API', mockAPI);
});

inject(function ($q) {
mockAPI.newRequest = function (path, conf) {
var defer = $q.defer();
defer.resolve({ "status": 1, "message": "", "validation_errors": [], "data": [{ "Id": 25, "Name": "Warszawa", "LocalCount": 25, "EventCount": 39 }] });
return defer.promise;
};
});
});

// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, API) {
API = API;
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope,
API : API
});
}));

it('checks if MainCtrl exist', function () {
expect(MainCtrl).toBeDefined();
});
});


but it fails. Im using Jasmine and Karma.


Aucun commentaire:

Enregistrer un commentaire