0

要测试的方法是

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"}

收到:[功能匿名]

4

1 回答 1

0

fetchCard是一个双箭头函数,所以你需要调用它两次才能真正调用它。

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

调用fetchCard(44)返回一个调度函数(一个 thunk)。您将需要调用fetchCard(44)(dispatch),或使用中间件,以便您可以调用dispatch(fetchCard(44))

于 2021-02-23T21:48:29.530 回答