describe('Using jest.fn() for Custom Mocking', () => {
let mockAxiosGet;
beforeEach(() => {
mockAxiosGet = jest.fn(); // Create a custom mock function
axios.get = mockAxiosGet; // Override axios.get with the mock function
});
afterEach(() => {
jest.restoreAllMocks();
});
it('mocks API with custom jest.fn()', async () => {
const data = { name: 'Jane Doe' };
mockAxiosGet.mockResolvedValueOnce({ data });
const result = await fetchData('https://api.example.com/user/1');
expect(result).toEqual(data);
expect(mockAxiosGet).toHaveBeenCalledWith('https://api.example.com/user/1');
});
it('mocks API with multiple jest.fn() calls', async () => {
const firstResponse = { name: 'John Doe' };
const secondResponse = { name: 'Jane Doe' };
mockAxiosGet
.mockResolvedValueOnce({ data: firstResponse })
.mockResolvedValueOnce({ data: secondResponse });
const firstResult = await fetchData('https://api.example.com/user/1');
const secondResult = await fetchData('https://api.example.com/user/2');
expect(firstResult).toEqual(firstResponse);
expect(secondResult).toEqual(secondResponse);
expect(mockAxiosGet).toHaveBeenCalledTimes(2);
});
});