如何模拟 $window 来对 AngularJS 服务进行单元测试? [英] how to mock $window to unit test AngularJS 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;
};
}]);
以下是我在引入 $window 服务之前的测试.这些测试当时运行良好,但是一旦我引入了 $window 服务,我就无法模拟它.
Below is my test from before introducing the $window service. These tests worked fine then, but once I introduced the $window service, I'm unable to 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();
});
});
});
我收到错误消息:TypeError: 'undefined' is not a function (evalating 'wdw.height()')
I am getting the error saying: TypeError: 'undefined' is not a function (evaluating 'wdw.height()')
我尝试使用 $provider 和 spyOn 方法,但没有一个有效.请帮忙.
I tried using the $provider and the spyOn methods, but none are working. Please help.
阿伦
推荐答案
显然height()和width()函数不正确.我将它们更改为 innerHeight 和 innerWidth 属性.
Apparently the height() and the width() functions 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've added it again here.
这篇关于如何模拟 $window 来对 AngularJS 服务进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!