Skip to content

Instantly share code, notes, and snippets.

@devotdev
Created December 5, 2024 15:01
Show Gist options
  • Save devotdev/1ed2104d73ded5aeadc568f6262d9b1c to your computer and use it in GitHub Desktop.
Save devotdev/1ed2104d73ded5aeadc568f6262d9b1c to your computer and use it in GitHub Desktop.
Using afterEach for cleanup
describe('Error Handling Tests', () => {
beforeEach(() => {
jest.clearAllMocks();
});
afterEach(() => {
// Restore all mocks after each test
jest.restoreAllMocks();
});
it('handles network error correctly', async () => {
const errorMessage = 'Network Error';
axios.get.mockRejectedValue(new Error(errorMessage)); // Simulate a network error
await expect(fetchData('https://api.example.com/user/1')).rejects.toThrow(errorMessage);
expect(axios.get).toHaveBeenCalledWith('https://api.example.com/user/1');
});
it('handles server error (500) correctly', async () => {
const errorResponse = {
response: { status: 500, data: { message: 'Internal Server Error' } }
};
axios.get.mockRejectedValue(errorResponse); // Simulate a 500 error
await expect(fetchData('https://api.example.com/user/1')).rejects.toThrow('Internal Server Error');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment