lundi 20 juillet 2015

Unit test basic factory that uses $window with Angular

I have a basic third-party service and I'm trying to unit-test it. I can't get it to 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 an error', function() {
      function fn() { delete $window.examplePlugin; }
      expect(fn).toThrowError();
   });
});

Aucun commentaire:

Enregistrer un commentaire