angularjs – 如何模拟在提供者私有函数中手动注入的$window?

前端之家收集整理的这篇文章主要介绍了angularjs – 如何模拟在提供者私有函数中手动注入的$window?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下提供者:

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);
    });

});

我的问题是,如何在Test#1和Test#2中模拟$window以便它们成功?我已经尝试使用$provide.value和spyOn来处理无数个对象,但我似乎无法模拟$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相关文章