Skip to content

Instantly share code, notes, and snippets.

@devotdev
Last active December 5, 2024 14:48
Show Gist options
  • Save devotdev/db4413b54c66066292f3fe0c9933235c to your computer and use it in GitHub Desktop.
Save devotdev/db4413b54c66066292f3fe0c9933235c to your computer and use it in GitHub Desktop.
Writing unit tests for GET requests
describe('GET Request Tests', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('fetches successfully data from an API', async () => {
const data = { id: 1, name: 'John Doe' };
axios.get.mockResolvedValue({ data });
const result = await fetchData('https://api.example.com/user/1');
expect(result).toEqual(data);
expect(axios.get).toHaveBeenCalledWith('https://api.example.com/user/1');
});
it('fetches data error from an API', async () => {
const errorMessage = 'Network Error';
axios.get.mockRejectedValue(new Error(errorMessage));
await expect(fetchData('https://api.example.com/user/1')).rejects.toThrow(errorMessage);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment