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 ofimport { 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