Test React.useEffect on Enzyme
Lumin

Lumin @ilumin

Location:
Bangkok, Thailand
Joined:
Jan 25, 2018

Test React.useEffect on Enzyme

Publish Date: Oct 20 '21
5 0

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 😆

Comments 0 total

    Add comment