'how to pass screen.height & screen.width in vue test case | Jest Framework
I have used screen.height & screen.width for js operations. I can't able to pass the test case. (code coverage). I am using vue utils - Jest framework. below My js code
const clientWidth = this.clientWidth ? this.clientWidth : screen.width;
const clientHeight = this.clientHeight ? this.clientHeight : screen.height;
Below what i have tried in my test case
it('should set the height of window screen', () =>{
Object.defineProperty(HTMLElement.prototype, 'screen', {
height: {
value: 100,
}
configurable: true,
});
How to write test case for this scenario.
Solution 1:[1]
Try like this. It will work.
global.screen.width = 300;
global.screen.height = 540;
Solution 2:[2]
In this case screen
is window.screen
, which is an instance of window.Screen
. In both browsers and Jest's simplified DOM implementation (jsdom) it consists of read-only properies that are implemented with property descriptors.
Either screen
property can be mocked on window
object with Object.defineProperty
, or width
and height
can be mocked separately on either Screen.prototype
or screen
with Object.defineProperty
.
Mocking a property with Jest spy allows for automatic clean-up after each test without restoring property descriptors in afterEach
, also reduces the boilerplate caused by the use of Object.defineProperty
manually:
jest.spyOn(screen, 'height', 'get').mockReturnValue(100);
expect(screen.height).toBe(100);
// evaluate piece of code that uses `screen`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ramprakash jagadeesan |
Solution 2 |