如何在测试自定义AngularJS提供程序时注入$window ?

时间:2023-01-21 12:03:44

I need to unit test a custom provider overriding the $windowProvider.

我需要对自定义提供程序进行单元测试,以覆盖$windowProvider。

provider.js

provider.js

angular
  .module('customProvider', [])

  .provider('cprovider', [
    '$windowProvider',
    function ($windowProvider) {
      var $window = $windowProvider.$get();

      var platform = function () {
        // some code there use $window
      };

      this.platform = platform;

      this.$get = function () {
        return {
          platform: platform
        };
      };
    }
  ]);

cprovider.spec.js

cprovider.spec.js

describe('cprovider', function () {
  var cprovider, mockWindow;

  describe("xxxx", function () {
    beforeEach(function () {
      mockWindow = {navigator: {userAgent: 'xxxx'}};


      module('customProvider', function ($provide) {
          $provide.value('$window', 'mockWindow');
      });

      inject(function (_cprovider_) {
        cprovider = _cprovider_;
      });
    });

    it('should something', function () {
      // Arrange and Act in beforeEach.

      // Assert. WON'T WORK
      expect(cprovider.platform()).toBe('xxx');
    });
  });
});

Can't mock properly the $windowProvider. Anyone knows how can I do that?

不能正确地模拟$windowProvider。有人知道我怎么做吗?

1 个解决方案

#1


3  

You can spyOn $window:

你可以spyOn $窗口:

beforeEach(function () {
    angular.mock.module('customProvider');
    inject(function (_$window_, _cprovider_) {
        cprovider = _cprovider_;
        $window = _$window_;
        spyOn($window, 'alert');
    });
});

Complete fiddle here

这里完整的小提琴

#1


3  

You can spyOn $window:

你可以spyOn $窗口:

beforeEach(function () {
    angular.mock.module('customProvider');
    inject(function (_$window_, _cprovider_) {
        cprovider = _cprovider_;
        $window = _$window_;
        spyOn($window, 'alert');
    });
});

Complete fiddle here

这里完整的小提琴