Mauro Mauro - 4 months ago 38
AngularJS Question

How can I inject $window when testing a custom AngularJS provider?

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?

Answer

You can spyOn $window:

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

Complete fiddle here

Comments