| // 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'); | |
| }); | |
| }); |