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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
|
- import { fetchWithProxy } from '../src/fetch';
- import {
- checkGoogleSheetAccess,
- fetchCsvFromGoogleSheetAuthenticated,
- fetchCsvFromGoogleSheetUnauthenticated,
- writeCsvToGoogleSheet,
- } from '../src/googleSheets';
- import logger from '../src/logger';
- import { createMockResponse } from './util/utils';
- import type { CsvRow } from '../src/types';
- interface MockSpreadsheets {
- get: jest.Mock;
- values: {
- get: jest.Mock;
- update: jest.Mock;
- };
- batchUpdate: jest.Mock;
- }
- jest.mock('../src/fetch', () => ({
- fetchWithProxy: jest.fn(),
- }));
- const mockSpreadsheetsApi = {
- get: jest.fn(),
- values: {
- get: jest.fn(),
- update: jest.fn(),
- },
- batchUpdate: jest.fn(),
- };
- // Update mock setup for better auth handling
- const mockAuthClient = {
- getClient: jest.fn().mockResolvedValue({}),
- };
- // Mock Google Sheets API
- jest.mock('@googleapis/sheets', () => {
- return {
- sheets: jest.fn(() => ({
- spreadsheets: mockSpreadsheetsApi,
- })),
- auth: {
- GoogleAuth: jest.fn(() => mockAuthClient),
- },
- };
- });
- describe('Google Sheets Integration', () => {
- const TEST_SHEET_URL = 'https://docs.google.com/spreadsheets/d/1234567890/edit';
- const TEST_SHEET_URL_WITH_GID =
- 'https://docs.google.com/spreadsheets/d/1234567890/edit?gid=98765';
- beforeEach(() => {
- jest.clearAllMocks();
- });
- describe('checkGoogleSheetAccess', () => {
- it('should return public:true for accessible sheets', async () => {
- jest.mocked(fetchWithProxy).mockResolvedValue(createMockResponse({ status: 200 }));
- const result = await checkGoogleSheetAccess(TEST_SHEET_URL);
- expect(result).toEqual({ public: true, status: 200 });
- expect(fetchWithProxy).toHaveBeenCalledWith(TEST_SHEET_URL);
- });
- it('should return public:false for inaccessible sheets', async () => {
- jest.mocked(fetchWithProxy).mockResolvedValue(createMockResponse({ status: 403 }));
- const result = await checkGoogleSheetAccess(TEST_SHEET_URL);
- expect(result).toEqual({ public: false, status: 403 });
- expect(fetchWithProxy).toHaveBeenCalledWith(TEST_SHEET_URL);
- });
- it('should handle network errors gracefully', async () => {
- jest.mocked(fetchWithProxy).mockRejectedValue(new Error('Network error'));
- const result = await checkGoogleSheetAccess(TEST_SHEET_URL);
- expect(result).toEqual({ public: false });
- expect(logger.error).toHaveBeenCalledWith(
- `Error checking sheet access: ${new Error('Network error')}`,
- );
- });
- });
- describe('fetchCsvFromGoogleSheetUnauthenticated', () => {
- it('should fetch and parse CSV data correctly', async () => {
- const mockCsvData = 'header1,header2\nvalue1,value2';
- const expectedUrl = `${TEST_SHEET_URL.replace(/\/edit.*$/, '/export')}?format=csv`;
- jest.mocked(fetchWithProxy).mockResolvedValue(
- createMockResponse({
- text: () => Promise.resolve(mockCsvData),
- }),
- );
- const result = await fetchCsvFromGoogleSheetUnauthenticated(TEST_SHEET_URL);
- expect(result).toEqual([{ header1: 'value1', header2: 'value2' }]);
- expect(fetchWithProxy).toHaveBeenCalledWith(expectedUrl);
- });
- it('should handle gid parameter correctly', async () => {
- const mockCsvData = 'header1,header2\nvalue1,value2';
- const baseUrl = TEST_SHEET_URL_WITH_GID.replace(/\/edit.*$/, '/export');
- const expectedUrl = `${baseUrl}?format=csv&gid=98765`;
- jest.mocked(fetchWithProxy).mockResolvedValue(
- createMockResponse({
- text: () => Promise.resolve(mockCsvData),
- }),
- );
- await fetchCsvFromGoogleSheetUnauthenticated(TEST_SHEET_URL_WITH_GID);
- expect(fetchWithProxy).toHaveBeenCalledWith(expectedUrl);
- });
- it('should throw error on non-200 response', async () => {
- jest.mocked(fetchWithProxy).mockResolvedValue(createMockResponse({ status: 403 }));
- await expect(fetchCsvFromGoogleSheetUnauthenticated(TEST_SHEET_URL)).rejects.toThrow(
- 'Failed to fetch CSV from Google Sheets URL',
- );
- });
- });
- describe('fetchCsvFromGoogleSheetAuthenticated', () => {
- const spreadsheets = mockSpreadsheetsApi as MockSpreadsheets;
- beforeEach(() => {
- jest.clearAllMocks();
- // Set up default sheet response
- spreadsheets.get.mockResolvedValue({
- data: {
- sheets: [
- {
- properties: {
- sheetId: 0,
- title: 'Sheet1',
- },
- },
- {
- properties: {
- sheetId: 98765,
- title: 'TestSheet',
- },
- },
- ],
- },
- });
- });
- it('should fetch and parse authenticated sheet data', async () => {
- const mockResponse = {
- data: {
- values: [
- ['header1', 'header2', 'header3'],
- ['value1', 'value2'],
- ],
- },
- };
- spreadsheets.values.get.mockResolvedValue(mockResponse);
- const result = await fetchCsvFromGoogleSheetAuthenticated(TEST_SHEET_URL);
- expect(result).toEqual([{ header1: 'value1', header2: 'value2', header3: '' }]);
- expect(spreadsheets.get).toHaveBeenCalledWith({
- spreadsheetId: '1234567890',
- auth: mockAuthClient,
- });
- expect(spreadsheets.values.get).toHaveBeenCalledWith({
- spreadsheetId: '1234567890',
- range: 'Sheet1',
- auth: mockAuthClient,
- });
- });
- it('should handle gid parameter correctly', async () => {
- spreadsheets.values.get.mockResolvedValue({
- data: {
- values: [['header'], ['value']],
- },
- });
- await fetchCsvFromGoogleSheetAuthenticated(TEST_SHEET_URL_WITH_GID);
- expect(spreadsheets.get).toHaveBeenCalledWith({
- spreadsheetId: '1234567890',
- auth: mockAuthClient,
- });
- expect(spreadsheets.values.get).toHaveBeenCalledWith({
- spreadsheetId: '1234567890',
- range: 'TestSheet',
- auth: mockAuthClient,
- });
- });
- it('should throw error for invalid sheet URL', async () => {
- await expect(fetchCsvFromGoogleSheetAuthenticated('invalid-url')).rejects.toThrow(
- 'Invalid Google Sheets URL',
- );
- });
- it('should throw error when no sheets found', async () => {
- spreadsheets.get.mockResolvedValue({
- data: {
- sheets: [],
- },
- });
- await expect(fetchCsvFromGoogleSheetAuthenticated(TEST_SHEET_URL)).rejects.toThrow(
- 'No sheets found in spreadsheet',
- );
- });
- it('should throw error when sheet with gid not found', async () => {
- await expect(
- fetchCsvFromGoogleSheetAuthenticated(
- 'https://docs.google.com/spreadsheets/d/1234567890/edit?gid=99999',
- ),
- ).rejects.toThrow('Sheet not found for gid: 99999');
- });
- });
- describe('Range behavior and backwards compatibility', () => {
- const spreadsheets = mockSpreadsheetsApi as MockSpreadsheets;
- beforeEach(() => {
- jest.clearAllMocks();
- // Set up default sheet response
- spreadsheets.get.mockResolvedValue({
- data: {
- sheets: [
- {
- properties: {
- sheetId: 0,
- title: 'Sheet1',
- },
- },
- ],
- },
- });
- });
- it('should retrieve all data when using sheet name only (no range specified)', async () => {
- const mockResponse = {
- data: {
- values: [
- ['header1', 'header2', 'header3'],
- ['value1', 'value2', 'value3'],
- ['value4', 'value5', 'value6'],
- ],
- },
- };
- spreadsheets.values.get.mockResolvedValue(mockResponse);
- const result = await fetchCsvFromGoogleSheetAuthenticated(TEST_SHEET_URL);
- // Verify the API was called with just the sheet name
- expect(spreadsheets.values.get).toHaveBeenCalledWith({
- spreadsheetId: '1234567890',
- range: 'Sheet1',
- auth: mockAuthClient,
- });
- // Verify all data was returned
- expect(result).toEqual([
- { header1: 'value1', header2: 'value2', header3: 'value3' },
- { header1: 'value4', header2: 'value5', header3: 'value6' },
- ]);
- });
- it('should handle empty cells correctly with sheet name only', async () => {
- const mockResponse = {
- data: {
- values: [
- ['header1', 'header2', 'header3', 'header4'],
- ['value1', '', 'value3'], // Missing value2 and header4
- ['', 'value5', '', 'value7'], // Missing header1 and header3
- ],
- },
- };
- spreadsheets.values.get.mockResolvedValue(mockResponse);
- const result = await fetchCsvFromGoogleSheetAuthenticated(TEST_SHEET_URL);
- expect(result).toEqual([
- { header1: 'value1', header2: '', header3: 'value3', header4: '' },
- { header1: '', header2: 'value5', header3: '', header4: 'value7' },
- ]);
- });
- it('should handle sheets with many columns beyond Z', async () => {
- // Create headers for columns A through AZ (52 columns)
- const headers = [];
- for (let i = 0; i < 52; i++) {
- headers.push(`header${i + 1}`);
- }
- const row1 = headers.map((_, i) => `value${i + 1}`);
- const mockResponse = {
- data: {
- values: [headers, row1],
- },
- };
- spreadsheets.values.get.mockResolvedValue(mockResponse);
- const result = await fetchCsvFromGoogleSheetAuthenticated(TEST_SHEET_URL);
- // Verify all 52 columns were retrieved
- expect(Object.keys(result[0])).toHaveLength(52);
- expect(result[0].header52).toBe('value52');
- });
- it('should handle trailing empty rows and columns correctly', async () => {
- // According to Google Sheets API docs, trailing empty rows and columns are omitted
- const mockResponse = {
- data: {
- values: [
- ['header1', 'header2', 'header3'],
- ['value1', 'value2', ''], // Trailing empty cell
- ['value4', '', ''], // Two trailing empty cells
- // Trailing empty rows are not included in the response
- ],
- },
- };
- spreadsheets.values.get.mockResolvedValue(mockResponse);
- const result = await fetchCsvFromGoogleSheetAuthenticated(TEST_SHEET_URL);
- expect(result).toEqual([
- { header1: 'value1', header2: 'value2', header3: '' },
- { header1: 'value4', header2: '', header3: '' },
- ]);
- });
- it('should handle very wide sheets efficiently', async () => {
- // Create a sheet with 100 columns
- const headers = Array.from({ length: 100 }, (_, i) => `Col${i + 1}`);
- const row1 = Array.from({ length: 100 }, (_, i) => `Val${i + 1}`);
- const testData = [headers, row1];
- spreadsheets.get.mockResolvedValue({
- data: {
- sheets: [
- {
- properties: {
- sheetId: 0,
- title: 'WideSheet',
- },
- },
- ],
- },
- });
- spreadsheets.values.get.mockResolvedValue({
- data: { values: testData },
- });
- const result = await fetchCsvFromGoogleSheetAuthenticated(TEST_SHEET_URL);
- // Verify the API was called with just the sheet name (not a huge range)
- expect(spreadsheets.values.get).toHaveBeenCalledWith({
- spreadsheetId: '1234567890',
- range: 'WideSheet',
- auth: mockAuthClient,
- });
- // Verify all 100 columns were retrieved
- expect(Object.keys(result[0])).toHaveLength(100);
- expect(result[0].Col100).toBe('Val100');
- });
- it('should calculate correct column letters for write operations', async () => {
- // Test the column letter calculation for various sizes
- const testCases = [
- { cols: 1, expected: 'A' },
- { cols: 26, expected: 'Z' },
- { cols: 27, expected: 'AA' },
- { cols: 52, expected: 'AZ' },
- { cols: 53, expected: 'BA' },
- { cols: 702, expected: 'ZZ' },
- { cols: 703, expected: 'AAA' },
- ];
- for (const { cols, expected } of testCases) {
- jest.clearAllMocks(); // Clear mocks between iterations
- const headers = Array.from({ length: cols }, (_, i) => `col${i + 1}`);
- const mockRows: CsvRow[] = [
- headers.reduce((acc, header) => ({ ...acc, [header]: 'value' }), {}),
- ];
- spreadsheets.values.update.mockResolvedValue({});
- spreadsheets.batchUpdate.mockResolvedValue({});
- await writeCsvToGoogleSheet(mockRows, TEST_SHEET_URL);
- const updateCall = spreadsheets.values.update.mock.calls[0][0];
- const range = updateCall.range;
- const endColumn = range.match(/!A1:([A-Z]+)\d+/)?.[1];
- expect(endColumn).toBe(expected);
- }
- });
- });
- });
|