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();
});
});
});
You can definitely use spys to mock HTTP calls.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With