Reputation: 454
In angularJs app, I want to test the aboutService in jasmine. The About service returns data in the following format:
var companyObject = [{"CompanyName": "A", "Contact Number" : "123456789"}, {"CompanyName": "B", "Contact Number" : "1234567899"}]
angular
.module('TestModule')
.factory('aboutService', aboutService);
aboutService.$inject = ['$rootScope', '$http'];
function homeService($rootScope, $http) {
function getAboutData() {
return $http({
method: "GET",
url: API URL,
})
.then(getAboutDataSuccess);
function getAboutDataSuccess(results) {
return results;//Data about company telephone contact number in array
}
}
var aboutService = {
getAboutData: getAboutData,
};
}
In aboutServiceSpec, I want to test if the data returned by API i.e an array length is greater than 0 and is equal to is equal to a variable companyObject
I have tried the following code with Jasmine, but it does not works.
describe("Service: aboutService", function () {
var aboutService, $httpBackend, $rootScope, response;
var companyObject = [{ "CompanyName": "A", "Contact Number": "123456789" }, { "CompanyName": "B", "Contact Number": "1234567899" }]
beforeEach(module('TestModule'));
beforeEach(inject(function (_$httpBackend_, _aboutService_, _$rootScope_) {
$httpBackend = _$httpBackend_;
aboutService = _aboutService_;
$rootScope = _$rootScope_;
}));
it('Should get about details of comapny', function () {
$httpBackend.expectGET('URL');
//Donot know how to go forward from here
});
});
Upvotes: 0
Views: 850
Reputation: 10716
$httpBackend.expectGET('URL').respond(companyObject);
aboutService.getAboutData().then(function(result) {
expect(result).toEqual(...); //or whatever expectation you want to test
});
$httpBackend.flush();
EDIT What this code does is the following:
$httpBackend.expectGET(...).respond(...)
defines an expectation
of what requests the code under test and mocks the response to that
request .then
block chained to the
service returned by the promise (at this point, the promise of the
$http
request is not resolved yet) $httpBackend.flush()
resolves
the promise with the mock object specified earlier (only now are the expectations in the .then
block fired). It also has the
side effect of invalidating the test if the expected request has not
been madeUpvotes: 1