My test case for an axios method says the return type is an anonymous function

238 Views Asked by At

The method to be tested is

const fetchCard = (id) => async (dispatch) => {
    const response = await axiosWrapper.get(`/giftCards/${id}`);
    dispatch ({
        type: FETCH_CARD,
        payload: response
    })
}

The test file is :

import mockAxios from "axios";
import { fetchCard } from '../actions'

describe('Test GiftCards transaction', () => {
  it("fetchCard from Id", async () => {
    const mockData = {
      "id": 44,
      "senderEmail": "[email protected]",
      "receiverEmail": "[email protected]",
      "cardName": "Food Card",
      "cardPoints": "321",
      "cardShortDesc": "30% OFF",
      "cardImage": "https://images.gyfthd.png",
      "cardIssueDate": "Sun May 19 2019 15:43:25 GMT+0530 (India Standard Time)",
      "cardExpiryDate": "2019-05-31T00:00:00.000Z",
      "isRedeemed": false
    }
    mockAxios.get.mockImplementationOnce(() =>
      Promise.resolve({ data: mockData }),
    )

    const result = await fetchCard(44);

    console.log(result)
    expect(mockAxios.get).toHaveBeenCalledTimes(1);
  });
})

src/mocks/axios.js

const mockAxios = jest.genMockFromModule('axios')

// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios)

export default mockAxios

The received value:

Expected: {"cardExpiryDate": "2019-05-31T00:00:00.000Z", "cardImage": "https://images.gyfthd.png", "cardIssueDate": "Sun May 19 2019 15:43:25 GMT+0530 (India Standard Time)", "cardName": "Food Card", "cardPoints": "321", "cardShortDesc": "30% OFF", "id": 44, "isRedeemed": false, "receiverEmail": "[email protected]", "senderEmail": "[email protected]"}

Received: [Function anonymous]

1

There are 1 best solutions below

0
On

fetchCard is a double arrow function, so you need to call it twice to actually invoke it.

const fetchCard = (id) => async (dispatch) => {

Calling fetchCard(44) returns a function of dispatch (a thunk). You would need to call fetchCard(44)(dispatch), or use middleware such that you can call dispatch(fetchCard(44)).