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

时间:2014-04-02 16:10:39

标签: angularjs jasmine karma-runner karma-jasmine

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

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

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

无法正确模拟$ windowProvider。 任何人都知道我该怎么做?

1 个答案:

答案 0 :(得分:4)

你可以窥探$ window:

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

完整小提琴here