Skip to content

Commit 8c5417b

Browse files
authored
DEMOS-1043: Remove debug statements and fix refetchQueries (#546)
* Fix refetchQueries! * remove console.debug * Fix tests
1 parent 798f938 commit 8c5417b

File tree

2 files changed

+130
-33
lines changed

2 files changed

+130
-33
lines changed

client/src/components/dialog/document/AddDocumentDialog.test.tsx

Lines changed: 119 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,31 @@ import { describe, expect, it, vi } from "vitest";
77

88
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
99

10-
import { AddDocumentDialog, tryUploadingFileToS3 } from "./AddDocumentDialog";
10+
import {
11+
AddDocumentDialog,
12+
DOCUMENT_POLL_INTERVAL_MS,
13+
tryUploadingFileToS3,
14+
VIRUS_SCAN_MAX_ATTEMPTS,
15+
} from "./AddDocumentDialog";
1116

1217
let mockMutationFn = vi.fn();
1318
let mockLazyQueryFn = vi.fn();
19+
let mockRefetchQueries = vi.fn();
1420

1521
beforeEach(() => {
1622
mockMutationFn = vi.fn();
1723
mockLazyQueryFn = vi.fn();
24+
mockRefetchQueries = vi.fn();
1825

1926
vi.mock("@apollo/client", async () => {
2027
const actual = await vi.importActual("@apollo/client");
2128
return {
2229
...actual,
2330
useMutation: () => [mockMutationFn, { loading: false }],
2431
useLazyQuery: () => [mockLazyQueryFn, { loading: false }],
32+
useApolloClient: () => ({
33+
refetchQueries: mockRefetchQueries,
34+
}),
2535
};
2636
});
2737
});
@@ -220,7 +230,7 @@ describe("virus scan polling", () => {
220230

221231
await clickPromise;
222232
// Advance timer to allow polling to complete
223-
await vi.advanceTimersByTimeAsync(1000);
233+
await vi.advanceTimersByTimeAsync(DOCUMENT_POLL_INTERVAL_MS);
224234

225235
expect(mockLazyQueryFn).toHaveBeenCalledWith({
226236
variables: { documentId: "test-doc-id" },
@@ -277,9 +287,9 @@ describe("virus scan polling", () => {
277287

278288
await clickPromise;
279289
// Advance timers for each polling attempt (3 total)
280-
await vi.advanceTimersByTimeAsync(1000); // 1st poll (fails)
281-
await vi.advanceTimersByTimeAsync(1000); // 2nd poll (fails)
282-
await vi.advanceTimersByTimeAsync(1000); // 3rd poll (succeeds)
290+
await vi.advanceTimersByTimeAsync(DOCUMENT_POLL_INTERVAL_MS); // 1st poll (fails)
291+
await vi.advanceTimersByTimeAsync(DOCUMENT_POLL_INTERVAL_MS); // 2nd poll (fails)
292+
await vi.advanceTimersByTimeAsync(DOCUMENT_POLL_INTERVAL_MS); // 3rd poll (succeeds)
283293

284294
expect(mockLazyQueryFn).toHaveBeenCalledTimes(3);
285295
expect(onDocumentUploadSucceeded).toHaveBeenCalled();
@@ -325,11 +335,11 @@ describe("virus scan polling", () => {
325335
});
326336

327337
await clickPromise;
328-
// Advance timers to reach max attempts (10 * 1000ms)
329-
await vi.advanceTimersByTimeAsync(10000);
338+
// Advance timers to reach max attempts
339+
await vi.advanceTimersByTimeAsync(VIRUS_SCAN_MAX_ATTEMPTS * DOCUMENT_POLL_INTERVAL_MS);
330340

331-
// Should reach max attempts (10) and throw timeout error
332-
expect(mockLazyQueryFn).toHaveBeenCalledTimes(10);
341+
// Should reach max attempts and throw timeout error
342+
expect(mockLazyQueryFn).toHaveBeenCalledTimes(VIRUS_SCAN_MAX_ATTEMPTS);
333343
});
334344

335345
it("skips virus scan polling for localhost uploads", async () => {
@@ -376,6 +386,106 @@ describe("virus scan polling", () => {
376386
// Should not poll for virus scan in localhost mode
377387
expect(mockLazyQueryFn).not.toHaveBeenCalled();
378388
});
389+
390+
it("refetches queries after successful upload when refetchQueries is provided", async () => {
391+
mockMutationFn.mockResolvedValue({
392+
data: {
393+
uploadDocument: {
394+
presignedURL: "https://s3.amazonaws.com/test-bucket/test-file",
395+
documentId: "test-doc-id",
396+
},
397+
},
398+
});
399+
400+
mockLazyQueryFn.mockResolvedValue({
401+
data: { documentExists: true },
402+
});
403+
404+
vi.mocked(globalThis.fetch).mockResolvedValue({ ok: true } as Response);
405+
406+
const onDocumentUploadSucceeded = vi.fn();
407+
const refetchQueries = ["GetDocuments", "GetApplicationDocuments"];
408+
409+
render(
410+
<ToastProvider>
411+
<AddDocumentDialog
412+
onClose={vi.fn()}
413+
applicationId="test-app-id"
414+
onDocumentUploadSucceeded={onDocumentUploadSucceeded}
415+
documentTypeSubset={["General File"]}
416+
refetchQueries={refetchQueries}
417+
/>
418+
</ToastProvider>
419+
);
420+
421+
const file = new File(["content"], "test.pdf", { type: "application/pdf" });
422+
fireEvent.change(screen.getByTestId(FILE_INPUT_TEST_ID), {
423+
target: { files: [file] },
424+
});
425+
426+
const uploadBtn = screen.getByTestId(UPLOAD_DOCUMENT_BUTTON_TEST_ID);
427+
await waitFor(() => expect(uploadBtn).toBeEnabled());
428+
429+
const clickPromise = new Promise<void>((resolve) => {
430+
fireEvent.click(uploadBtn);
431+
setTimeout(() => resolve(), 0);
432+
});
433+
434+
await clickPromise;
435+
await vi.advanceTimersByTimeAsync(DOCUMENT_POLL_INTERVAL_MS);
436+
437+
expect(onDocumentUploadSucceeded).toHaveBeenCalled();
438+
expect(mockRefetchQueries).toHaveBeenCalledWith({ include: refetchQueries });
439+
});
440+
441+
it("does not call refetchQueries when not provided", async () => {
442+
mockMutationFn.mockResolvedValue({
443+
data: {
444+
uploadDocument: {
445+
presignedURL: "https://s3.amazonaws.com/test-bucket/test-file",
446+
documentId: "test-doc-id",
447+
},
448+
},
449+
});
450+
451+
mockLazyQueryFn.mockResolvedValue({
452+
data: { documentExists: true },
453+
});
454+
455+
vi.mocked(globalThis.fetch).mockResolvedValue({ ok: true } as Response);
456+
457+
const onDocumentUploadSucceeded = vi.fn();
458+
459+
render(
460+
<ToastProvider>
461+
<AddDocumentDialog
462+
onClose={vi.fn()}
463+
applicationId="test-app-id"
464+
onDocumentUploadSucceeded={onDocumentUploadSucceeded}
465+
documentTypeSubset={["General File"]}
466+
/>
467+
</ToastProvider>
468+
);
469+
470+
const file = new File(["content"], "test.pdf", { type: "application/pdf" });
471+
fireEvent.change(screen.getByTestId(FILE_INPUT_TEST_ID), {
472+
target: { files: [file] },
473+
});
474+
475+
const uploadBtn = screen.getByTestId(UPLOAD_DOCUMENT_BUTTON_TEST_ID);
476+
await waitFor(() => expect(uploadBtn).toBeEnabled());
477+
478+
const clickPromise = new Promise<void>((resolve) => {
479+
fireEvent.click(uploadBtn);
480+
setTimeout(() => resolve(), 0);
481+
});
482+
483+
await clickPromise;
484+
await vi.advanceTimersByTimeAsync(DOCUMENT_POLL_INTERVAL_MS);
485+
486+
expect(onDocumentUploadSucceeded).toHaveBeenCalled();
487+
expect(mockRefetchQueries).not.toHaveBeenCalled();
488+
});
379489
});
380490

381491
describe("tryUploadingFileToS3", () => {

client/src/components/dialog/document/AddDocumentDialog.tsx

Lines changed: 11 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import React from "react";
2-
import { gql, useLazyQuery, useMutation } from "@apollo/client";
2+
import { gql, useLazyQuery, useMutation, useApolloClient } from "@apollo/client";
33

44
import { DocumentType, PhaseName, UploadDocumentInput } from "demos-server";
55
import { DocumentDialog, DocumentDialogFields } from "components/dialog/document/DocumentDialog";
@@ -20,8 +20,8 @@ export const DOCUMENT_EXISTS_QUERY = gql`
2020
}
2121
`;
2222

23-
const VIRUS_SCAN_MAX_ATTEMPTS = 10;
24-
const DOCUMENT_POLL_INTERVAL_MS = 1_000;
23+
export const VIRUS_SCAN_MAX_ATTEMPTS = 10;
24+
export const DOCUMENT_POLL_INTERVAL_MS = 2_000;
2525
const LOCALHOST_URL_PREFIX = "http://localhost";
2626

2727
/**
@@ -70,9 +70,8 @@ export const AddDocumentDialog: React.FC<AddDocumentDialogProps> = ({
7070
onDocumentUploadSucceeded,
7171
}) => {
7272
const { showError } = useToast();
73-
const [uploadDocumentTrigger] = useMutation(UPLOAD_DOCUMENT_QUERY, {
74-
refetchQueries,
75-
});
73+
const client = useApolloClient();
74+
const [uploadDocumentTrigger] = useMutation(UPLOAD_DOCUMENT_QUERY);
7675

7776
const [checkDocumentExists] = useLazyQuery(DOCUMENT_EXISTS_QUERY, {
7877
fetchPolicy: "network-only",
@@ -89,32 +88,22 @@ export const AddDocumentDialog: React.FC<AddDocumentDialogProps> = ({
8988
};
9089

9190
const waitForVirusScan = async (documentId: string): Promise<void> => {
92-
console.debug(`[AddDocumentDialog] Starting virus scan polling for document: ${documentId}`);
9391
for (let attempt = 0; attempt < VIRUS_SCAN_MAX_ATTEMPTS; attempt++) {
94-
console.debug(
95-
`[AddDocumentDialog] Polling attempt ${attempt + 1}/${VIRUS_SCAN_MAX_ATTEMPTS}`
96-
);
9792
const { data } = await checkDocumentExists({
9893
variables: { documentId },
9994
});
10095

10196
if (data?.documentExists === true) {
102-
console.debug(`[AddDocumentDialog] Document exists check passed on attempt ${attempt + 1}`);
10397
return;
10498
}
10599

106-
console.debug(
107-
`[AddDocumentDialog] Document not yet available, waiting ${DOCUMENT_POLL_INTERVAL_MS}ms before retry`
108-
);
109-
110100
await new Promise((resolve) => setTimeout(resolve, DOCUMENT_POLL_INTERVAL_MS));
111101
}
112102

113103
throw new Error("Waiting for virus scan timed out");
114104
};
115105

116106
const handleUpload = async (dialogFields: DocumentDialogFields): Promise<void> => {
117-
console.debug(`[AddDocumentDialog] Starting upload for file: ${dialogFields.file?.name}`);
118107
if (!dialogFields.file) {
119108
showError("No file selected");
120109
return;
@@ -146,32 +135,30 @@ export const AddDocumentDialog: React.FC<AddDocumentDialogProps> = ({
146135
throw new Error("Upload response from the server was empty");
147136
}
148137

149-
console.debug(
150-
`[AddDocumentDialog] Received presigned URL and documentId: ${uploadResult.documentId}`
151-
);
152-
153138
// Local development mode - skip S3 upload and virus scan
154139
if (uploadResult.presignedURL.startsWith(LOCALHOST_URL_PREFIX)) {
155140
onDocumentUploadSucceeded?.();
141+
if (refetchQueries) {
142+
await client.refetchQueries({ include: refetchQueries });
143+
}
156144
return;
157145
}
158146

159147
if (!uploadResult.presignedURL) {
160148
throw new Error("Could not get presigned URL from the server");
161149
}
162150

163-
console.debug(`[AddDocumentDialog] Starting S3 upload for file: ${dialogFields.file.name}`);
164151
const response = await tryUploadingFileToS3(uploadResult.presignedURL, dialogFields.file);
165152
if (!response.success) {
166-
console.debug(`[AddDocumentDialog] S3 upload failed: ${response.errorMessage}`);
167153
showError(response.errorMessage);
168154
throw new Error(response.errorMessage);
169155
}
170156

171-
console.debug("[AddDocumentDialog] S3 upload successful, starting virus scan wait");
172157
await waitForVirusScan(uploadResult.documentId);
173-
console.debug("[AddDocumentDialog] Upload and virus scan completed successfully");
174158
onDocumentUploadSucceeded?.();
159+
if (refetchQueries) {
160+
await client.refetchQueries({ include: refetchQueries });
161+
}
175162
};
176163

177164
return (

0 commit comments

Comments
 (0)