ReactJs testing useEffect hook with enzyme

Posted by itungnt on Sunday, March 1, 2020

Reactjs testing with enzyme doesn’t work with new React hook like useEffect, you need to:

  • Mock useEffect hook with: jest.spyOn
  • Use React.useEffect instead of import { useEffect } from 'react'

component.js

export default function YourComponent() {
    const [data, setData] = useState(null)

    React.useEffect(() => {
        YourService.yourfunction()
            .then(data => setData(data))
    }, [])

    return (
        <Table/>
    )
}

component.test.js


import { shallow } from "enzyme"

describe("<YourComponent>", () => {
    let wrapper

    beforeEach(() => {
        // given
        YourService.yourfunction = jest.fn(() =>
            Promise.resolve(testData)
        )
        jest.spyOn(React, "useEffect").mockImplementationOnce(f => f())

        // when
        wrapper = shallow(<YourComponent/>)
    })

    // then
    it("renders properly", () => {
        expect(wrapper.find(Table)).toMatchSnapshot()
    })
})

comments powered by Disqus