Reputation: 16648
The problem I'm trying to solve is the ability to test my factory using Jasmine.
Below is a copy of my app and factory:
var app = angular.module('app', []);
app.factory('service', function ($http) {
return {
getCustomers: function (callback) {
$http.get('/Home/Customers').success(callback);
},
getProfile: function (callback, viewModel) {
$http.post('/Home/Profiles', JSON.stringify(viewModel), {
headers: {
'Content-Type': 'application/json'
}
}).success(callback);
}
};
});
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
I have also setup jasmine but I'm having trouble testing the above "getCustomers" and "getProfile".
Below is my current attempt:
describe("getCustomers", function (service) {
beforeEach(module('service'));
describe('getCustomers', function () {
it("should return a list of customers", inject(function(getCustomers){
expect(getCustomers.results).toEqual(["david", "James", "Sam"]);
}))
})
});
This would be really helpful if someone could provide an example of how to test both "getCustomers" and "getProfile" in two separete tests.
Kind regards.
Upvotes: 4
Views: 5379
Reputation: 54543
You can mock the Http GET request and test the service like this
describe("getCustomers", function (service) {
beforeEach(module('app'));
var service, httpBackend;
beforeEach(function () {
angular.mock.inject(function ($injector) {
httpBackend = $injector.get('$httpBackend');
service = $injector.get('service');
})
});
describe('getCustomers', function () {
it("should return a list of customers", inject(function () {
httpBackend.expectGET('/Home/Customers').respond(['david', 'James', 'Sam']);
service.getCustomers(function (result) {
expect(result).toEqual(["david", "James", "Sam"]);
});
httpBackend.flush();
}))
})
});
Upvotes: 4