7

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?

4

1 回答 1

12

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

于 2020-03-23T15:54:31.390 回答