Search code examples
angularjstestingjasminewidthscreen

How to test screen.width condition using karma and jasmine


For a while now I'm struggling with testing a simple if statement in my controller.

if (screen.width <= 768) {
                $location.hash('map');
                $anchorScroll();
            }

I found a way to spawn the browser with a different size but it didn't work the screen.width always stays the same. Is there a way to cover that part of the code?


Solution

  • Yes, There is a way.

    You will have to replace screen.width with $window.screen.width and you can mock window object in jasmine.

    Then, You can mock window using below code:

    var window = {
      screen : {
          width : 500
         }
    };
    

    now in your spec file : in beforeEach block

    $controller('controllerName', {$window : window});