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

时间:2014-07-11 16:05:28

标签: angularjs unit-testing karma-jasmine angular-mock

我有以下提供商:

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

});

我的问题是,如何在$windowTest #1中模仿Test #2以便它们成功?我尝试过使用$provide.valuespyOn对于无数个对象,但我似乎无法模仿$window.navigator.userAgent的值来运行我的测试。

我该如何解决这个问题?

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

1 个答案:

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

});

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