DEV Community

Discussion on: Clean Up Async Requests in `useEffect` Hooks

Collapse
 
pyyding profile image
Kaspar Püüding

Cool but how do you test it?

Collapse
 
pyyding profile image
Kaspar Püüding • Edited

Something like this:

  it('should fetch on mount and abort call on unmount', async () => {
    const abortCall = jest.fn()
    global.AbortController = class {

      signal = 'test-signal'

      abort = abortCall

    }

    fetch.mockResolvedValueOnce({ result: { body: { test: 'test-value' } } })

    const { getByText, unmount } = render(<MyComponent />)

    expect(getByText('Loading...')).toBeInTheDocument()

    const expectedOptions = { signal: 'test-signal' }
    expect(fetch).toHaveBeenCalledWith('test-url', expectedOptions)
    expect(fetch).toHaveBeenCalledTimes(1)

    await waitForElement(() => getByText('test-value'))

    expect(abortCall).toHaveBeenCalledTimes(0)

    unmount()

    expect(abortCall).toHaveBeenCalledTimes(1)
  })
Collapse
 
pallymore profile image
Yurui Zhang

I think that might work - however it seems to be testing implementation details - which might be ok if your hook does nothing when aborted.

For testing with fetch I usually use something like sinon's fakeServer. You can intercept requests but not respond to it - unmount the component (or anything that triggers an abort) and check if corresponding side effects are firing (or not firing - e.g. no actions were dispatched)