DEV Community

Lumin
Lumin

Posted on

Test React.useEffect on Enzyme

What

Normally (in my legacy code base) I've always found that my legacy code from the old project use shallow to test the component. But the problem is shallow doesn't trigger React.useEffect that's why I googling and not it here.

Example component to test

const Component = ({ callMe }) => {
  React.useEffect(() => {
    callMe()
  }, [])
  return <>Yikes</>
}
Enter fullscreen mode Exit fullscreen mode

Work around

description('Component', () => {
  it('should call `callMe` on mount', () => {
    const mockCallMe = jest.fn()
    mount(<Component callMe={mockCallMe} />)

    expect(mockCallMe).toHaveBeenCalled()
  })
})
Enter fullscreen mode Exit fullscreen mode

to solve this issue, instead of use shallow just use mount, the difference is mount are really mount component but shallow are just render

Long term

switch to @testing-library if you have effort πŸ˜†

Top comments (0)