So I've a similar useCase defined in stackover flow answer, but somewhat different. I have a react component and it has two useEffect hooks. One useEffect hook is used at first time render and other once the dependency in that useEffect hook changes. I tried mocking getDelivery but it comes from a custom hook defined in app.
// App.tsx
const App = () => {
const [deliveryType, setDeliveryType] = useState([])
const { DeliveryStatusService } = useServices()
const deliveryStatusService = new DeliveryStatusService()
const { deliveryId } = useParams()
useEffect(() => {
setup()
}, [])
useEffect(() => {
if (deliveryType) {
console.log("DeliveryType is Set")
}
}, [deliveryType])
const setup = async () => {
const response = await deliveryStatusService.getDelivery(deliveryId) // this call comes from custom hook and external service
setDeliveryType(response)
}
return (
<>
<div>{!deliveryType ? <div>Render Loading</div> : <div>Data loaded with {deliveryType}</div>}</div>
</>
)
}
I tried to mock it out as stated in above article as follows using Jest and Enzyme but if I console.log(wrapper.debug) I still get Render Loading
and not Data loaded with {deliveryType}
.
I tried mocking it like this :
const getDelivery = jest.fn()
const DeliveryStatusService = jest.fn().mockImplementation(() => ({
getDelivery,
}))
it('mock getDelivery', () => {
const wrapper = mount(<ServiceProvider services={{DeliveryStatus}}>
<App />
</ServiceProvider>
getDelivery.mockReturnValue(
Promise.resolve(
... dummyData
),
)
await act(flushPromises)
wrapper.update()
await act(flushPromises)
console.log(wrapper.debug())
console.log(wrapper.debug()) yields the following output:
<ServiceProvider services={{...}}>
<App>
<div>
<div>
Render Loading
</div>
</div>
<App>
</ServiceProvider>
Am I not mocking correctly so that I would never have Data loaded
div
?