mercredi 7 octobre 2015

How to mock $window.innerWidth AngularJS with Jasmine

In my AngularJS app I have factory:

    ( function () {
    "use strict";

    angular
        .module("app")
        .factory("DeviceTypeService", DeviceTypeService);

    function DeviceTypeService($window) {

        function isTablet () {
            var width = $window.innerWidth;
            return width > 639;
        }

        return {
            isTablet: isTablet
        };
    }

})();

I need to perform a unit test for it with Jasmin, running on Karma. I tried different solutions, but my test fails every time.

One of my solutions:

'use strict';

describe('DeviceType Service', function(){
 var mock_window,
     sut;

 beforeEach(function(){
   module('app');
   mock_window = {innerWidth: 1000};

   module(function($provide){
        $provide.value('$window', mock_window);
    });
 });

 beforeEach(inject(function(_DeviceTypeService_){
   sut = _DeviceTypeService_;
 }));

 it('isTablet() method shoul return "true" if $window.innerWidth > 639 px', function(){
    expect(sut.isTablet()).toBeTruthy();
  });
});

This test return FAILED Expected false to be truthy. I almost tried to create SPY for $window.innerWidth but it doesn't work too.

Please show me my mistake or give some reference to a working code.

Aucun commentaire:

Enregistrer un commentaire