How to Test Angular Factory Objects Using Jasmine

The problem I'm trying to solve is the ability to test my factory with Jasmine.

Below is a copy of my application 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 also have jasmine installed, but I am having problems 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 very useful if someone could provide an example of how to test "getCustomers" and "getProfile" in two separate tests.

Sincerely.

+4
source share
1 answer

You can mock the Http GET request and test a 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(); })) }) }); 

Working demo

+4
source

Source: https://habr.com/ru/post/1499708/


All Articles