3

I need to unit test a custom provider overriding the $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');
    });
  });
});

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

4

1 回答 1

4

你可以窥探 $window:

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

在这里完成小提琴

于 2014-04-02T19:42:26.747 回答