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?
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With