要测试的方法是
const fetchCard = (id) => async (dispatch) => {
const response = await axiosWrapper.get(`/giftCards/${id}`);
dispatch ({
type: FETCH_CARD,
payload: response
})
}
测试文件是:
import mockAxios from "axios";
import { fetchCard } from '../actions'
describe('Test GiftCards transaction', () => {
it("fetchCard from Id", async () => {
const mockData = {
"id": 44,
"senderEmail": "abc@gmail.com",
"receiverEmail": "abc@gmail.com",
"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/模拟/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
收到的值:
预期:{“cardExpiryDate”:“2019-05-31T00:00:00.000Z”,“cardImage”:“ https://images.gyfthd.png ”,“cardIssueDate”:“2019 年 5 月 19 日星期日 15:43:25 GMT+0530(印度标准时间)”、“cardName”:“食品卡”、“cardPoints”:“321”、“cardShortDesc”:“30% OFF”、“id”:44、“isRedeemed”:false、“ receiverEmail": "abc@gmail.com", "senderEmail": "abc@gmail.com"}
收到:[功能匿名]