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]
fetchCard
is a double arrow function, so you need to call it twice to actually invoke it.Calling
fetchCard(44)
returns a function of dispatch (a thunk). You would need to callfetchCard(44)(dispatch)
, or use middleware such that you can calldispatch(fetchCard(44))
.