-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapi.test.ts
More file actions
46 lines (36 loc) Β· 1.77 KB
/
api.test.ts
File metadata and controls
46 lines (36 loc) Β· 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { getUserById } from '@/state/user/api';
import { getAxiosInstance } from '@/services/axiosInstance';
import { API_ENDPOINTS } from '@/utils/api/endpoints';
import { mapApiResponseToUserState } from '@/utils/mappers/apiMappers';
jest.mock('@/services/axiosInstance', () => ({
getAxiosInstance: jest.fn(),
}));
jest.mock('@/utils/mappers/apiMappers', () => ({
mapApiResponseToUserState: jest.fn(),
}));
describe('getUserById', () => {
it('should return user data when the API call is successful', async () => {
const mockUserId = '123';
const mockApiResponse = { name: 'John Doe', email: 'john.doe@example.com' };
const mockMappedUserData = { name: 'John Doe', email: 'john.doe@example.com', role: 'User' };
const mockAxiosInstance = {
get: jest.fn().mockResolvedValue({ data: mockApiResponse }),
};
(getAxiosInstance as jest.Mock).mockReturnValue(mockAxiosInstance);
(mapApiResponseToUserState as jest.Mock).mockReturnValue(mockMappedUserData);
const result = await getUserById(mockUserId);
expect(mockAxiosInstance.get).toHaveBeenCalledWith(API_ENDPOINTS.GET_USER_BY_ID.replace('{id}', mockUserId));
expect(mapApiResponseToUserState).toHaveBeenCalledWith(mockApiResponse);
expect(result).toEqual(mockMappedUserData);
});
it('should throw an error when the API call fails', async () => {
const mockUserId = '123';
const mockError = new Error('API error');
const mockAxiosInstance = {
get: jest.fn().mockRejectedValue(mockError),
};
(getAxiosInstance as jest.Mock).mockReturnValue(mockAxiosInstance);
await expect(getUserById(mockUserId)).rejects.toThrow('Failed to fetch user data.');
expect(mockAxiosInstance.get).toHaveBeenCalledWith(API_ENDPOINTS.GET_USER_BY_ID.replace('{id}', mockUserId));
});
});