简体   繁体   中英

How to mock fetch in React Jest

I am new to react testing, I am trying to test my async function by mocking fetch requests. However, when I ran the test, it gave me a false positive. I expected the mock fetch to return the mock data but it returns the actual data from the database. What am I doing wrongly.

Here is the actual function I am testing.

export const fetchVisit = async (currentUserId, visitDate) => {
  try {
    const visitData = await axios.post(
      `${BASE_URL}/visit/${currentUserId}`,
      visitDate
    );
   
    const {
      data: {
        data: { visit },
      },
    } = visitData;

    
    return visit;
  } catch (err) {
    return err;
  }
};

Here is the function in my test suite

const mockData = [
  {
    serviceusersToVisit: [[Object], [Object]],
    _id: '1',
    currentUserId: '123',
    __v: 0,
    dateOfVisit: '2022-08-31T00:00:00.000Z',
  },
];

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve(mockData),
  })
);

describe('MOCK FETCH OF fetchVisit', () => {
  it('should fetch a single visit', async () => {
    let visitDate = {
      dateOfVisit: '2022-08-31T00:00:00.000+00:00',
    };

    let visit = await fetchVisit('123', visitDate);
    console.log(visit);
    expect(visit.length).toBe(1);
  });
}

You are using axios.post() to make HTTP request, you should mock axios.post() method instead of fetch .

Try:

jest.spyOn(axios, 'post').mockResolvedValue({ data: mockData })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM