gpt4 book ai didi

angularjs - 如何模拟在提供者私有(private)函数中手动注入(inject)的 $window?

转载 作者:行者123 更新时间:2023-12-04 21:57:17 25 4
gpt4 key购买 nike

我有以下提供者:

angular.module('MyApp').provider('MyDevice', function () {

var ngInjector = angular.injector(['ng']),
$window = ngInjector.get('$window');

function isMobileDevice () {
return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/)
.test($window.navigator.userAgent || $window.navigator.vendor || $window.opera);
}

this.$get = function () {
return {
isDesktop: function () {
return !isMobileDevice();
},
isMobile: function () {
return isMobileDevice();
}
};
};

});

以及以下测试规范:
describe('MyDeviceProvider', function () {

var myDevice;

beforeEach(function () {
inject(['MyDevice', function (_myDevice_) {
myDevice = _myDevice_;
}]);
});

it('Test #1', function () {
// Mock '$window.navigator.userAgent' to "desktop"
expect(myDevice.isDesktop()).toEqual(true);
expect(myDevice.isMobile()).toEqual(false);
});

it('Test #2', function () {
// Mock '$window.navigator.userAgent' to "mobile"
expect(myDevice.isDesktop()).toEqual(false);
expect(myDevice.isMobile()).toEqual(true);
});

});

我的问题是,我如何模拟 $window在这两个 Test #1Test #2所以他们成功了吗? 我试过 $provide.valuespyOn对于无数的对象,但我似乎无法模拟 $window.navigator.userAgent 的值运行我的测试。

我该如何解决这个问题?

P.S:以上代码仅作为我的问题的演示,由于应用程序的特殊要求,我无法将提供程序更改为服务。

最佳答案

非常粗略地,您可以执行以下操作:

describe('MyDeviceProvider', function () {

var myDevice,
$window,
navigator;

beforeEach(function () {
inject(['MyDevice', '$window', function (_myDevice_, _$window_) {
myDevice = _myDevice_;
$window = _$window_;
}]);

// Save the original navigator object
navigator = $window.navigator;
});

afterEach(function () {
$window.navigator = navigator;
});

it('Test #1', function () {
// Mock the entire navigator object to "desktop"
$window.navigator = {
userAgent: "desktop" // Use a real "desktop" user agent
};

// Mock '$window.navigator.userAgent' to "desktop"
expect(myDevice.isDesktop()).toEqual(true);
expect(myDevice.isMobile()).toEqual(false);
});

it('Test #2', function () {
// Mock the entire navigator object to "desktop"
$window.navigator = {
userAgent: "mobile" // Use a real "mobile" user agent
};
// Mock '$window.navigator.userAgent' to "mobile"
expect(myDevice.isDesktop()).toEqual(false);
expect(myDevice.isMobile()).toEqual(true);
});

});

您也应该测试模仿不同浏览器的不同模拟。

关于angularjs - 如何模拟在提供者私有(private)函数中手动注入(inject)的 $window?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24702003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com