Skip to content

Instantly share code, notes, and snippets.

@devotdev
Created December 5, 2024 14:46
Show Gist options
  • Save devotdev/56413f4b79720bf565f0bf2bf5abf26c to your computer and use it in GitHub Desktop.
Save devotdev/56413f4b79720bf565f0bf2bf5abf26c to your computer and use it in GitHub Desktop.
Mocking API calls with Jest
// 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