Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 264
Georgi Stefanov Avatar asked Jan 04 '23 23:01

Georgi Stefanov


1 Answers

I'm using Angular 8. I used karma-viewport plugin to mock the screen size and it works well to me.

The package is available at https://www.npmjs.com/package/karma-viewport.

In the karma.conf.js I have to add viewport to frameworks and require the package in plugins.

My karma.conf.js:

frameworks: ['jasmine', '@angular-devkit/build-angular', 'viewport'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-junit-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma'),
      require('karma-viewport')
    ],

In my .spec.ts file I added the viewport var declaration:

declare const viewport: any;

Changed the size in the "it" function, called my method that changes a variable according to the screen size and after checked the result. In my case the property width of the component should be 240 when the screen size is less than 700px:

it('test xyz', () => {
    viewport.set(320, 240);
    component.changeHeightByScreenSize();
    expect(component.width).toEqual(240);
  });
like image 158
Jordan Ferr Avatar answered Jan 13 '23 15:01

Jordan Ferr