1

I'm trying to unit test a simple custom hook, getWindowWidth(), but I can not get the window in Enzyme to resize.

I'm using enzyme to mount a component that uses the hook, setting the width of the window object, forcing a re-render, yet the window width never changes.

Here is the hook:

import { useState, useEffect } from 'react';

export default function getWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  });

  return width;
}

and here is my test:

import React from 'react';
import { mount } from 'enzyme';
import getWindowWidth from './getWindowWidth';

// simulate window resize
function fireResize(width) {
  window.innerWidth = width;
  window.dispatchEvent(new Event('resize'))
}
// Test component that uses the Hook
function EffecfulComponent() {
  const viewport = getWindowWidth()
  return <span>{viewport}</span>
}

test('should show updated window width', () => {
  const wrapper = mount(<EffecfulComponent />)
  expect(wrapper.text()).toEqual('1024');
  fireResize(320);
  wrapper.update();
  expect(wrapper.text()).toEqual('320');
});

I expected the window to resize to 320, but it stays at 1024 (the default).

1 Answer 1

1

The problem is that Jest makes use of jsdom which doesn’t provide the window object. You need to mock in order to test it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.