angularjs - Unit test basic factory that uses $window with Angular -


i have basic third-party service , i'm trying unit-test it. can't throwerror.

example

angular.module('example')    .factory('examplefactory', ['$window', function($window) {         if(typeof $window.exampleplugin === 'undefined') {            throw new error('plugin not available');         } else {           return $window.exampleplugin;         }    }]); 

unit test

describe('factory', function() {    var $window, examplefactory;     beforeeach(module('example'));     beforeeach(function() {        module(function($provide) {           $provide.value('$window', {});       });        inject(function(_$window_, _examplefactory_) {          examplefactory = _examplefactory_;          $window = _$window_;       });    });     it('should exist', function() {       $window.exampleplugin = {};       expect($window.exampleplugin).tobedefined();    });     it('should throw error', function() {       function fn() { delete $window.exampleplugin; }       expect(fn).tothrowerror();    }); }); 

given you've shown, can think of this

describe('factory', function() {     var $window;      beforeeach(module('example', function($provide) {         $provide.value('$window', $window = {});     });      it('returns exampleplugin if set', function() {         $window.exampleplugin = 'foo';         inject(function(examplefactory) {             expect(examplefactory).tobe($window.exampleplugin);         });     });      it('throws error if exampleplugin not set', function() {         // not entirely sure have wrapped correctly         // trial , error should there         expect(function() {inject(function(examplefactory) {})}).tothrow();     }); }); 

the main thing need set desired properties of $window before injecting factory.


Comments