-
-
Save devotdev/a8fe0a22d04c688559de924ed582ff5e to your computer and use it in GitHub Desktop.
Using jest.fn() for custom mocking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment