jest-react-hooks-shallow
jest-react-hooks-shallow copied to clipboard
Clash with mocking React to work around useRef problems
useRef()
also doesn't work with shallow rendering if the ref.current
value is handled by passing the ref to a DOM node or a component with ref forwarding. In this case, the ref will always be undefined
with shallow rendering.
This can be worked around by mocking out useRef()
and making it return a mock value that doesn't crash the component that's being tested. However, a mock list this:
jest.mock('react', () => ({
...jest.requireActual('react'),
useRef: arg => (typeof arg === 'undefined' ? { current: { getBoundingClientRect: () => ({ left: 0 }) } } : {current: arg}),
}));
will override jest-react-hooks-shallow's mock useEffect()
and revert it to React's default implementation.
I've been able to work around the issue like this:
import React, {useEffect} from 'react';
import mockUseEffect from 'jest-react-hooks-shallow/lib/mock-use-effect/mock-use-effect';
jest.mock('react', () => ({
...jest.requireActual('react'),
useEffect: jest.fn(),
useRef: arg => (typeof arg === 'undefined' ? { current: { getBoundingClientRect: () => ({ left: 0 }) } } : {current: arg}),
}));
then
useEffect.mockImplementation(mockUseEffect());
instead of withHooks()
in every test case where withHooks()
would normally be used.
It would be nice if the library would offer a more elegant solution for this, either by mocking out useRef()
as well or re-exporting mock-use-effect
so that we don't have to have an ugly import like above.
Hi @MilosRasic ,
I apologise for not looking into this issue. I'll try to have a look at it. Also, you're more than welcome to contribute to the library :).
Thanks for the solution @mikeborozdin! +1 for integrating this into the library