DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Teerasak Vichadee
Teerasak Vichadee

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)

๐ŸŒš Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.