Testing axios with axios-mock-adapter
I have been using axios to make network requests to a webservice from a React + Redux app. For testing the requests from the React app, I have been using axios-mock-adapter. The following is the action which makes the network request that I want to test.
It uses a Redux thunk to dispatch the request action retrieveCollectionRequest()
before the network request happens.
The next action, retrieveSingleCollectionSuccess(response))
happens after the request is successfully resolved. This action just passes the response from the request to my reducer which stores the response in my Redux store.
I dispatch the action elsewhere in one of my components.
I want to test that when I dispatch this action it makes a network request to my webservice then stores the response in my Redux store if it is successful.
The MockAdapter
replys to my GET
request with a 200 status code so that the request resolves successfully and passes in a collection as the response. collectionsState
is the object in my Redux store where I store the response. I test that the collection which shows up in the collectionsState
matches the data in the mock.onGet()
reply handler.
Debugging
I had a few issues with this test at first. The data that I used in the reply handler to respond to my request did not match the data that the request resolved. This resulted in my request receiving a 404 status code.
I also wanted to see what my request was doing when the mock adapter handles it. To accomplish this I can use this bit of code to inspect it;
The github repo for axios-mock-adapter
has some nice tests itself which helped me resolve the bugs I ran into.