3

I am using axios cancel token to do cleanup in my useEffect hook as shown below. When I run tests I get error shown below. I am using react testing library and jest to test my app. I am also using mock service worker to intercept and handle requests. Is there a way I can mock the axios.CancelToken.source call to resolve the failing tests?

UseEffect hook:

useEffect(() => {

 const source = axios.CancelToken.source()
 axios.get(URLS.GET_DATA,
  {
    cancelToken: source.token
  })
  .then(response => {
    setData(response.data)
  })
  .catch((error) => {
    if (axios.isCancel(error)) {
    } else {
      console.log('Handle Error')
    }
  })

return () => {
  source.cancel()
}

}, [building, numberOfDeletions, numberOfUpdates, numberOfAdds], [])

Test Server Service Worker:

const server = setupServer(
rest.get('/api/data/'), (req, res, ctx) => {
return res(
  ctx.status(200),
  ctx.json({ data: data })
)})

Failing test:

it('should render title to page', () => {
const { getByText } = render(<EditIndex />)
const heading = getByText('Edit Items')

expect(heading.textContent).toEqual('Edit Items')
})

Error message:

Error Message

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
GaB
  • 157
  • 1
  • 3
  • 12
  • 2
    The error likely means that you're already mocking Axios but you didn't show this. Otherwise it would have `CancelToken`. – Estus Flask Oct 19 '20 at 17:00

1 Answers1

-1

The second solution in this post worked for me. As the above comment mentions, I was already mocking axios and I didn't have CancelToken defined in the mock. I ended up modifying the mock by simply passing in axios and everything passed; CancelToken was no longer undefined.

import axios from 'axios';
jest.mock('axios');
Arron J. Linton
  • 681
  • 2
  • 11
  • 28