Repository navigation
Expand file tree
/
Copy pathgithub.test.ts
More file actions
249 lines (210 loc) · 8.33 KB
/
Copy pathgithub.test.ts
File metadata and controls
249 lines (210 loc) · 8.33 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/* eslint-disable @typescript-eslint/no-explicit-any */
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
fetchGitHubContributions,
fetchUserProfile,
fetchUserRepos,
getFullDashboardData,
} from './github';
import type { ContributionCalendar } from '../types';
const mockCalendar: ContributionCalendar = {
totalContributions: 42,
weeks: [
{
contributionDays: [
{ contributionCount: 3, date: '2024-06-10' },
{ contributionCount: 0, date: '2024-06-11' },
{ contributionCount: 5, date: '2024-06-12' },
],
},
],
};
function mockResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
describe('fetchGitHubContributions', () => {
beforeEach(() => {
vi.spyOn(global, 'fetch');
});
afterEach(() => {
vi.restoreAllMocks();
});
it('returns the contribution calendar on a successful response', async () => {
vi.mocked(fetch).mockResolvedValue(
mockResponse({
data: {
user: { contributionsCollection: { contributionCalendar: mockCalendar } },
},
})
);
const result = await fetchGitHubContributions('octocat');
expect(result).toEqual(mockCalendar);
});
it('sends a POST request to the GitHub GraphQL endpoint with the correct body', async () => {
vi.mocked(fetch).mockResolvedValue(
mockResponse({
data: {
user: { contributionsCollection: { contributionCalendar: mockCalendar } },
},
})
);
await fetchGitHubContributions('octocat');
expect(fetch).toHaveBeenCalledOnce();
const [url, options] = vi.mocked(fetch).mock.calls[0];
expect(url).toBe('https://api.github.com/graphql');
expect(options?.method).toBe('POST');
// Make sure the username is wired into the GraphQL variables, not hardcoded.
const body = JSON.parse(options?.body as string);
expect(body.variables).toEqual({ login: 'octocat' });
expect(body.query).toContain('contributionCalendar');
});
it('works correctly for a brand-new user who has zero contribution weeks', async () => {
const emptyCalendar: ContributionCalendar = { totalContributions: 0, weeks: [] };
vi.mocked(fetch).mockResolvedValue(
mockResponse({
data: {
user: { contributionsCollection: { contributionCalendar: emptyCalendar } },
},
})
);
const result = await fetchGitHubContributions('new-user');
expect(result).toEqual(emptyCalendar);
});
it('throws with the status code when the server returns 500', async () => {
vi.mocked(fetch).mockResolvedValue(mockResponse({ message: 'Internal Server Error' }, 500));
await expect(fetchGitHubContributions('octocat')).rejects.toThrow(
'GitHub GraphQL API returned status 500'
);
});
it('throws with the status code when the server returns 401 (expired or missing token)', async () => {
// A 401 is the most common real-world failure — bad or missing GITHUB_PAT.
vi.mocked(fetch).mockResolvedValue(mockResponse({ message: 'Unauthorized' }, 401));
await expect(fetchGitHubContributions('octocat')).rejects.toThrow(
'GitHub PAT is invalid or missing'
);
});
it('throws when fetch itself rejects due to a network failure', async () => {
vi.mocked(fetch).mockRejectedValue(new Error('Failed to fetch'));
await expect(fetchGitHubContributions('octocat')).rejects.toThrow('Failed to fetch');
});
it('throws the first GraphQL error when the API returns an errors array', async () => {
vi.mocked(fetch).mockResolvedValue(
mockResponse({
data: { user: null },
errors: [{ message: 'Bad credentials' }, { message: 'Some other error' }],
})
);
// Only the first error surfaces — the source always reads errors[0].
await expect(fetchGitHubContributions('octocat')).rejects.toThrow('Bad credentials');
});
it('throws a descriptive "user not found" error when the username does not exist on GitHub', async () => {
vi.mocked(fetch).mockResolvedValue(mockResponse({ data: { user: null } }));
await expect(fetchGitHubContributions('ghost-user-xyz')).rejects.toThrow(
'GitHub user "ghost-user-xyz" not found'
);
});
});
describe('fetchUserProfile', () => {
beforeEach(() => vi.spyOn(global, 'fetch'));
afterEach(() => vi.restoreAllMocks());
it('returns profile data on success', async () => {
vi.mocked(fetch).mockResolvedValue(mockResponse({ login: 'octocat', name: 'The Octocat' }));
const result = await fetchUserProfile('octocat');
expect(result.name).toBe('The Octocat');
});
it('throws "User not found" on 404', async () => {
vi.mocked(fetch).mockResolvedValue(mockResponse({ message: 'Not Found' }, 404));
await expect(fetchUserProfile('ghost')).rejects.toThrow('User not found');
});
it('throws status code error on other failures', async () => {
vi.mocked(fetch).mockResolvedValue(mockResponse({ message: 'Error' }, 500));
await expect(fetchUserProfile('octocat')).rejects.toThrow('GitHub REST API error: 500');
});
});
describe('fetchUserRepos', () => {
beforeEach(() => vi.spyOn(global, 'fetch'));
afterEach(() => vi.restoreAllMocks());
it('returns repos data on success', async () => {
vi.mocked(fetch).mockResolvedValue(mockResponse([{ name: 'repo1' }]));
const result = await fetchUserRepos('octocat');
expect(result[0].name).toBe('repo1');
});
it('throws status code error on failure', async () => {
vi.mocked(fetch).mockResolvedValue(mockResponse({ message: 'Error' }, 500));
await expect(fetchUserRepos('octocat')).rejects.toThrow('GitHub REST API error: 500');
});
});
describe('getFullDashboardData', () => {
beforeEach(() => vi.spyOn(global, 'fetch'));
afterEach(() => vi.restoreAllMocks());
it('returns full dashboard data correctly', async () => {
vi.mocked(fetch).mockImplementation(async (url: any) => {
if (typeof url === 'string' && url.includes('/users/octocat/repos')) {
return mockResponse([
{ stargazers_count: 10, language: 'TypeScript' },
{ stargazers_count: 5, language: 'TypeScript' },
{ stargazers_count: 20, language: 'Rust' },
]);
}
if (typeof url === 'string' && url.includes('/users/octocat')) {
return mockResponse({
login: 'octocat',
name: 'The Octocat',
avatar_url: 'avatar.png',
public_repos: 3,
followers: 10,
following: 5,
created_at: '2020-01-01T00:00:00Z',
bio: 'Hello world',
location: 'Earth',
});
}
// GraphQL
return mockResponse({
data: {
user: { contributionsCollection: { contributionCalendar: mockCalendar } },
},
});
});
const result = await getFullDashboardData('octocat');
expect(result.profile.username).toBe('octocat');
expect(result.profile.stats.stars).toBe(35);
expect(result.languages).toEqual([
{ name: 'TypeScript', percentage: 67, color: '#3178c6' },
{ name: 'Rust', percentage: 33, color: '#dea584' },
]);
expect(result.insights).toBeDefined();
expect(result.commitClock).toBeDefined();
});
it('throws if any fetch fails', async () => {
vi.mocked(fetch).mockImplementation(async (url: any) => {
if (typeof url === 'string' && url.includes('/users/octocat/repos')) {
return mockResponse([]);
}
if (typeof url === 'string' && url.includes('/users/octocat')) {
throw new Error('Network error');
}
return mockResponse({
data: { user: { contributionsCollection: { contributionCalendar: mockCalendar } } },
});
});
await expect(getFullDashboardData('octocat')).rejects.toThrow('Network error');
});
it('throws unknown error for non-error throws', async () => {
vi.mocked(fetch).mockImplementation(async (url: any) => {
if (typeof url === 'string' && url.includes('/users/octocat/repos')) {
return mockResponse([]);
}
if (typeof url === 'string' && url.includes('/users/octocat')) {
throw 'String error';
}
return mockResponse({
data: { user: { contributionsCollection: { contributionCalendar: mockCalendar } } },
});
});
await expect(getFullDashboardData('octocat')).rejects.toThrow('An unknown error occurred');
});
});