lundi 8 octobre 2018

Testing redux-thunk with an axios request

I am trying to test the following action, mocking a successful flow:

export const search = searchTerm => async dispatch => {
  dispatch(searchRequest(searchTerm));
  try {
    const searchResults = await getSearchData(searchTerm);
    dispatch(searchSuccess(searchResults));
    dispatch(searchComplete());
  } catch (e) {
    dispatch(searchFail(e));
    dispatch(searchComplete());
  }
};

getSearchData:

export const getSearchData = async searchTerm => {
  const {
    data: {
      data: { results: booksFromSearch },
    },
  } = await get(`/search?title=${searchTerm}`);

  return booksFromSearch;
}; 

The URL endpoint matches http://localhost:8080/search?title=Great (for example).

Below is my test case, I am mocking the response object:

const mock = new MockAdapter(axios);

it("should fire a successful search", () => {
    const response = [{ id: 1 }, { id: 2 }];
    mock.onGet("http://localhost:8080/search?title=Great").reply(200, response);
    store.dispatch(search("Great"));
    expect(store.getActions()).toEqual([
      { type: SEARCH_REQUEST, payload: { searchTerm: "Great" } },
      { type: SEARCH_SUCCESS },
      { type: SEARCH_COMPLETE },
    ]);
  });

However, when I run the test case I only see SEARCH_REQUEST being fired.

Expected value to equal:
      [{"payload": {"searchTerm": "Great"}, "type": "SEARCH_REQUEST"}, {"type": "SEARCH_SUCCESS"}, {"type": "SEARCH_COMPLETE"}]
    Received:
      [{"payload": {"searchTerm": "Great"}, "type": "SEARCH_REQUEST"}]

Aucun commentaire:

Enregistrer un commentaire