Skip to content

Commit 5a314d5

Browse files
committed
test: improve test coverage for fetchData
1 parent fd8e448 commit 5a314d5

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { fetchData } from '../../src/api';
2+
3+
const mockFetch = global.fetch as jest.MockedFunction<typeof fetch>;
4+
5+
const createResponse = ({
6+
ok = true,
7+
status = 200,
8+
json = undefined,
9+
text = '',
10+
}: {
11+
ok?: boolean;
12+
status?: number;
13+
json?: unknown;
14+
text?: string;
15+
}) => ({
16+
ok,
17+
status,
18+
json: jest.fn().mockResolvedValue(json),
19+
text: jest.fn().mockResolvedValue(text),
20+
}) as unknown as Response;
21+
22+
describe('fetchData', () => {
23+
beforeEach(() => {
24+
jest.clearAllMocks();
25+
});
26+
27+
it('returns parsed json when responseType is json', async () => {
28+
const payload = { value: 'test' };
29+
mockFetch.mockResolvedValueOnce(createResponse({ json: payload }));
30+
31+
await expect(fetchData<typeof payload>('/api/config', 'json')).resolves.toEqual(payload);
32+
expect(mockFetch).toHaveBeenCalledWith('/api/config');
33+
});
34+
35+
it('returns text when responseType is text', async () => {
36+
mockFetch.mockResolvedValueOnce(createResponse({ text: 'diff content' }));
37+
38+
await expect(fetchData<string>('/api/diff/test.md', 'text')).resolves.toBe('diff content');
39+
});
40+
41+
it('logs and rethrows http errors', async () => {
42+
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
43+
44+
mockFetch.mockResolvedValueOnce(createResponse({ ok: false, status: 500 }));
45+
46+
await expect(fetchData('/api/config', 'json')).rejects.toThrow('HTTP error! status: 500');
47+
expect(consoleErrorSpy).toHaveBeenCalledWith(
48+
'Error fetching from /api/config:',
49+
expect.any(Error),
50+
);
51+
});
52+
53+
it('logs and rethrows fetch failures', async () => {
54+
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
55+
const error = new Error('Network down');
56+
57+
mockFetch.mockRejectedValueOnce(error);
58+
59+
await expect(fetchData('/api/config', 'json')).rejects.toThrow(error);
60+
expect(consoleErrorSpy).toHaveBeenCalledWith('Error fetching from /api/config:', error);
61+
});
62+
});

0 commit comments

Comments
 (0)