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).