-
-
Save devotdev/56413f4b79720bf565f0bf2bf5abf26c to your computer and use it in GitHub Desktop.
Mocking API calls with Jest
This file contains 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
// api.test.js | |
const axios = require('axios'); | |
const fetchData = require('../api'); | |
// Mock the axios module | |
jest.mock('axios'); | |
describe('API Call Tests', () => { | |
// Reset all mocks before each test to ensure test isolation | |
beforeEach(() => { | |
jest.clearAllMocks(); | |
}); | |
it('fetches successfully data from an API', async () => { | |
const data = { name: 'John Doe' }; | |
// Mocking the resolved value of axios.get | |
axios.get.mockResolvedValue({ data }); | |
const result = await fetchData('https://example.com/user'); | |
expect(result).toEqual(data); | |
expect(axios.get).toHaveBeenCalledWith('https://example.com/user'); | |
}); | |
it('handles API error correctly', async () => { | |
const errorMessage = 'Network Error'; | |
// Mocking the rejected value of axios.get | |
axios.get.mockRejectedValue(new Error(errorMessage)); | |
await expect(fetchData('https://example.com/user')).rejects.toThrow(errorMessage); | |
expect(axios.get).toHaveBeenCalledWith('https://example.com/user'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment