Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set size of window in Jest and jest-dom and jsdom

I test the height of the window in Jest with jest-dom and jsdom.

With this code :

import '@testing-library/jest-dom'

describe('test window height'), () => {
  test('test the height'), () => {
    expect(window.innerHeight).toBe(150) // 150 is an arbitrary value for testing the test ! 
   }) 
 }) 

The result is an error that say :

Expected: 150

Received: 768

With innerWidth, the received value is 1024

That is great, it means that the size of window is testable with Jest and jest-dom.

But where does 768 and 1024 come from ? Is it the default values and will always be ? Is it configurable and how?

like image 780
Pepito Avatar asked Feb 25 '20 14:02

Pepito


People also ask

Does Jest use Jsdom?

Jest actually ships with jsdom and the environment already configured. You can override it with the testEnvironment setting. If you need to set up more aspects of the environment though, you can use the setupTestFrameworkScriptFile setting to point to a file that executes before all of your tests run.

How does Jest tests within a DOM environment?

How does Jest test within a DOM environment? Jest ships with jsdom, which simulates a DOM environment as if you were in a browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser.

What is Jest DOM for?

This allows you to check if an element is currently visible to the user. An element is visible if all the following conditions are met: it is present in the document. it does not have its css property display set to none.


1 Answers

The 768 and 1024 is a default, Jest is configuring jsdom for your test with.

You can overwrite window.innerHeight in your test. But TypeScript says no, because window is an unwritable member.

For me Object.defineProperty works as expected with TypeScript.

So with JEST this test should pass green:

describe('test window height', () => {
  it('test the height',
    () => {
      Object.defineProperty(window, 'innerHeight', {
        writable: true,
        configurable: true,
        value: 150,
      });

      window.dispatchEvent(new Event('resize'));

      expect(window.innerHeight).toBe(150);
    });
});

Example of use of Object.defineProperty with TS found here: How to test that a media query css applies to an element upon screen resize using jest and enzyme in reactjs

like image 158
Herr_Hansen Avatar answered Oct 19 '22 15:10

Herr_Hansen