How to taunt $ window to unit test AngularJS services?

Here is my service:

var services = angular.module('amdotcom.services', ['ngResource']); services.factory('homePageRes', ['$resource', '$window', function ($resource, $window) { var wdw = angular.element($window); return $resource('home/index', { height: wdw.height(), width: wdw.width() }); }]); services.factory('homePageLoader', ['homePageRes', '$q', function (homePageRes, $q) { return function () { var delay = $q.defer(); homePageRes.get(function (homePage) { delay.resolve(homePage); }, function () { delay.reject('Unable to fetch home page'); }); return delay.promise; }; }]); 

Below is my test before introducing the $ window service. These tests worked fine then, but as soon as I introduced the $ window service, I can’t mock it.

 describe('Services', function () { beforeEach(function () { module("amdotcom.services"); }); describe('homePageLoader', function () { var mockBackend, loader; beforeEach(inject(function ($httpBackend, homePageLoader) { mockBackend = $httpBackend; loader = homePageLoader; })); it('should return home page information', function () { mockBackend.expectGET('home/index?height=400&width=500').respond({ "Albums": [{ "Id": 2, "Name": "best shots" }] }); var homePageData; var promise = loader(); promise.then(function (homePg) { homePageData = homePg; }); expect(homePageData).toBeUndefined(); mockBackend.flush(); expect(homePageData.Albums[0].Id).toEqual(2); expect(homePageData.Albums[0].Name).toEqual("best shots"); }); afterEach(function () { mockBackend.verifyNoOutstandingExpectation(); mockBackend.verifyNoOutstandingRequest(); }); }); }); 

I get an error: TypeError: 'undefined' is not a function (evaluating "wdw.height ()")

I tried using the methods of $ provider and spyOn, but no one works. Please, help.

Arun

+6
source share
1 answer

Apparently the functions height () and width () are incorrect. I changed them to innerHeight and innerWidth properties.

 services.factory('homePageRes', ['$resource', '$window', function ($resource, $window) { return $resource('home/index', { height: $window.innerHeight, width: $window.innerWidth }); }]); beforeEach(function () { angular.mock.module("amdotcom.services", function ($provide) { var myMock = { innerHeight: 400, innerWidth: 500 }; $provide.value('$window', myMock); }); }); 

Since my comment above was not formatted and less readable, I added it again here.

+6
source

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


All Articles