0

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?

Simmi George
  • 145
  • 1
  • 3
  • 12
  • The setup method uses `deliveryId` which is changing, so you should add the dependency of `deliveryId` in first useEffect method so that it executes again based on changed prop value. – user1672994 May 06 '22 at 05:20
  • I wouldn't want to do that as ```deliveryId``` field has a timeStamp value so It should be set at once at the start otherwise it would re-render everytime and cause an inifinte loop of renders – Simmi George May 06 '22 at 05:24
  • Also, should you move the mock implementation of `getDelivery` before mounting the component? You can use beforeEach to all the mock implementation of `getDelivery` – user1672994 May 06 '22 at 08:18

0 Answers0