我有以下提供商:
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 #1
中模仿Test #2
以便它们成功?我尝试过使用$provide.value
和spyOn
对于无数个对象,但我似乎无法模仿$window.navigator.userAgent
的值来运行我的测试。
我该如何解决这个问题?
P.S:上面的代码仅作为我的问题的演示,由于应用程序的特殊要求,我无法将提供者更改为服务。
答案 0 :(得分:15)
非常粗略,您可以执行以下操作:
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);
});
});
您应该测试模仿不同浏览器的不同模拟。