-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.services.test.ts
More file actions
45 lines (40 loc) · 1.86 KB
/
Copy pathapp.services.test.ts
File metadata and controls
45 lines (40 loc) · 1.86 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
import { fetchUser, createTodo } from './app.services';
import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;
describe('app.services', () => {
describe('fetchUser', () => {
it('returns user data on success', async () => {
mockedAxios.get.mockResolvedValueOnce({ data: { name: 'Test User' } });
const data = await fetchUser();
expect(data).toEqual({ name: 'Test User' });
expect(mockedAxios.get).toHaveBeenCalledWith('https://raw.githubusercontent.com/hidaytrahman/hidaytrahman/main/me.json');
});
it('logs error and returns undefined on failure', async () => {
const error = new Error('Network error');
mockedAxios.get.mockRejectedValueOnce(error);
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
const data = await fetchUser();
expect(data).toBeUndefined();
expect(spy).toHaveBeenCalledWith(error);
spy.mockRestore();
});
});
describe('createTodo', () => {
it('returns data on success', async () => {
mockedAxios.post.mockResolvedValueOnce({ data: { id: 1, title: 'Test', completed: false } });
const result = await createTodo('Test', false);
expect(result).toEqual({ data: { id: 1, title: 'Test', completed: false }, error: null });
expect(mockedAxios.post).toHaveBeenCalledWith('https://jsonplaceholder.typicode.com/todos', { title: 'Test', completed: false });
});
it('returns error on failure', async () => {
const error = new Error('Post error');
mockedAxios.post.mockRejectedValueOnce(error);
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
const result = await createTodo('Test', false);
expect(result).toEqual({ data: null, error: 'Post error' });
expect(spy).toHaveBeenCalledWith(error);
spy.mockRestore();
});
});
});