我如何在嘲弄私人提供手动功能注入$窗口? [英] How do I mock $window injected manually in provider private function?
问题描述
我有以下提供:
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);
});
});
我的问题是,我怎么嘲笑 $窗口
在两个测试#1
和测试#2
所以他们是成功的吗我曾尝试与 $ provide.value
和 spyOn
无数的对象,但我似乎无法模拟的 $ window.navigator.userAgent
值来运行我的测试。
My question is, how do I mock $window
in both Test #1
and Test #2
so they are successful? I have tried with $provide.value
and spyOn
for countless objects, but I can't seem to mock the value of $window.navigator.userAgent
to run my tests.
我该如何解决这个问题?
How do I solve this?
P.S:在code以上仅作为我的问题的演示,我不能提供者转变成一个服务,因为应用程序的特殊要求
P.S: The code above acts only as a demonstration of my issue and I cannot change the provider into a service because of special requirements of the application.
推荐答案
很粗暴,你可以做到以下几点:
Very crudely, you could do the following:
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);
});
});
您应该测试不同嘲笑模仿不同的浏览器了。
You should test different mocks mimicking different browsers too.
这篇关于我如何在嘲弄私人提供手动功能注入$窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!