Back to listJavaScript
Jest Testing with Mocks
Lv.5608@mukitaro7 playsDec 28, 2025
Jest unit tests with mocking. Facebook's JavaScript testing framework.
preview.js
1const fetchUser = require('./fetchUser');2const axios = require('axios');3 4jest.mock('axios');5 6describe('fetchUser', () => {7 it('fetches user data successfully', async () => {8 const mockUser = { id: 1, name: 'John' };9 axios.get.mockResolvedValue({ data: mockUser });10 11 const result = await fetchUser(1);12 13 expect(axios.get).toHaveBeenCalledWith('/api/users/1');14 expect(result).toEqual(mockUser);15 });16 17 it('handles errors gracefully', async () => {18 axios.get.mockRejectedValue(new Error('Network Error'));19 20 await expect(fetchUser(1)).rejects.toThrow('Network Error');21 });22});Custom problems are not included in rankings