@thepalaceproject/circulation-admin 1.43.0-post.11 → 1.43.0-post.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,18 @@
1
1
  import * as React from "react";
2
- import { fireEvent } from "@testing-library/react";
2
+ import { installFormDataShim } from "../testUtils/formDataShim";
3
+ import { fireEvent, screen, waitFor } from "@testing-library/react";
4
+ import userEvent from "@testing-library/user-event";
3
5
  import { Collections } from "../../../src/components/Collections";
6
+ import CollectionsConnected from "../../../src/components/Collections";
4
7
  import renderWithContext from "../testUtils/renderWithContext";
8
+ import { renderWithProviders } from "../testUtils/withProviders";
9
+ import buildStore from "../../../src/store";
5
10
  import {
6
11
  CollectionsData,
7
12
  ConfigurationSettings,
8
13
  } from "../../../src/interfaces";
9
14
  import { defaultFeatureFlags } from "../../../src/utils/featureFlags";
10
15
 
11
- // NB: This adds tests to the already existing tests in:
12
- // - `src/components/__tests__/Collections-test.tsx`.
13
- //
14
- // Those tests should eventually be migrated here and
15
- // adapted to the Jest/React Testing Library paradigm.
16
-
17
16
  describe("Collections - associated library disclosure", () => {
18
17
  // ── Shared fixtures ───────────────────────────────────────────────────────
19
18
 
@@ -219,3 +218,332 @@ describe("Collections - associated library disclosure", () => {
219
218
  );
220
219
  });
221
220
  });
221
+
222
+ // These exercise behavior the disclosure tests above do not: the connect()
223
+ // wiring (mapStateToProps / mapDispatchToProps, which only run when the CONNECTED
224
+ // default export mounts), the marked-for-deletion list item, the
225
+ // confirm-before-disassociating-libraries behavior, the
226
+ // getChildContext().registerLibrary closure, the on-mount registrations fetch,
227
+ // and the delete flow.
228
+
229
+ describe("Collections - connected wiring, deletion, and registration", () => {
230
+ const allLibraries = [
231
+ { short_name: "nypl", name: "NYPL", uuid: "uuid-nypl" },
232
+ ];
233
+
234
+ const sysAdminConfig: Partial<ConfigurationSettings> = {
235
+ csrfToken: "",
236
+ featureFlags: defaultFeatureFlags,
237
+ roles: [{ role: "system" }],
238
+ };
239
+
240
+ afterEach(() => {
241
+ jest.restoreAllMocks();
242
+ });
243
+
244
+ describe("connected default export", () => {
245
+ // A loaded `libraries` slice persists through the on-mount collections fetch
246
+ // (the libraries reducer ignores that action), so mapStateToProps takes its
247
+ // `data.allLibraries` branch on every render.
248
+ const loadedLibrariesState = {
249
+ data: { libraries: allLibraries },
250
+ isFetching: false,
251
+ isEditing: false,
252
+ fetchError: null,
253
+ formError: null,
254
+ isLoaded: true,
255
+ responseBody: null,
256
+ successMessage: null,
257
+ };
258
+
259
+ const stubFetch = (body: unknown) =>
260
+ jest.spyOn(globalThis, "fetch").mockImplementation(
261
+ async () =>
262
+ new Response(JSON.stringify(body), {
263
+ status: 200,
264
+ headers: { "Content-Type": "application/json" },
265
+ })
266
+ );
267
+
268
+ it("wires mapStateToProps/mapDispatchToProps and marks a collection for deletion", async () => {
269
+ const listData = {
270
+ collections: [
271
+ { id: 2, protocol: "test protocol", name: "ODL" },
272
+ {
273
+ id: 3,
274
+ protocol: "test protocol",
275
+ name: "Enki",
276
+ marked_for_deletion: true,
277
+ },
278
+ ],
279
+ protocols: [{ name: "test protocol", label: "TP", settings: [] }],
280
+ };
281
+ stubFetch(listData);
282
+ const store = buildStore({
283
+ editor: { libraries: loadedLibrariesState },
284
+ } as any);
285
+
286
+ const { container } = renderWithProviders(
287
+ <CollectionsConnected csrfToken="token" />,
288
+ {
289
+ reduxProviderProps: { store },
290
+ appConfigSettings: sysAdminConfig,
291
+ }
292
+ );
293
+
294
+ // The list appears once the connected component's on-mount fetch resolves
295
+ // and mapStateToProps feeds the fetched data back in as props.
296
+ expect(
297
+ await screen.findByRole("heading", { level: 3, name: "ODL" })
298
+ ).toBeInTheDocument();
299
+
300
+ // The non-deleted collection has edit and delete controls.
301
+ const editLink = container.querySelector("a.edit-item");
302
+ expect(editLink.getAttribute("href")).toBe(
303
+ "/admin/web/config/collections/edit/2"
304
+ );
305
+
306
+ // The deleted collection renders a special item with no edit/delete
307
+ // controls and an explanatory message.
308
+ const deleted = container.querySelector(".deleted-collection");
309
+ expect(deleted).not.toBeNull();
310
+ expect(deleted).toHaveTextContent("Enki");
311
+ expect(deleted).toHaveTextContent(/cannot be edited/);
312
+ expect(deleted.querySelector("a.edit-item")).toBeNull();
313
+ expect(deleted.querySelector("button.delete-item")).toBeNull();
314
+ });
315
+ });
316
+
317
+ describe("edit mode: registration and additional content", () => {
318
+ // The reusable-components `Form` builds `new FormData(formElement)` on
319
+ // submit, which the unit jsdom env's undici FormData rejects; install the
320
+ // shared shim that reads the form's successful controls.
321
+ installFormDataShim();
322
+ it("fetches registrations on mount, renders task controls, and registers a library on click", async () => {
323
+ const user = userEvent.setup();
324
+ const registerLibrary = jest.fn().mockResolvedValue(undefined);
325
+ const fetchLibraryRegistrations = jest.fn().mockResolvedValue(undefined);
326
+ renderWithContext(
327
+ <Collections
328
+ data={
329
+ {
330
+ collections: [
331
+ {
332
+ id: 7,
333
+ protocol: "OPDS Import",
334
+ name: "An OPDS Collection",
335
+ libraries: [],
336
+ },
337
+ ],
338
+ protocols: [
339
+ {
340
+ name: "OPDS Import",
341
+ supports_registration: true,
342
+ supports_import: true,
343
+ settings: [],
344
+ library_settings: [],
345
+ },
346
+ ],
347
+ allLibraries,
348
+ } as any
349
+ }
350
+ editOrCreate="edit"
351
+ identifier="7"
352
+ fetchData={jest.fn()}
353
+ editItem={jest.fn().mockResolvedValue(undefined)}
354
+ deleteItem={jest.fn().mockResolvedValue(undefined)}
355
+ registerLibrary={registerLibrary}
356
+ fetchLibraryRegistrations={fetchLibraryRegistrations}
357
+ importCollection={jest.fn().mockResolvedValue(undefined)}
358
+ reapCollection={jest.fn().mockResolvedValue(undefined)}
359
+ csrfToken="token"
360
+ isFetching={false}
361
+ />,
362
+ sysAdminConfig
363
+ );
364
+
365
+ // componentDidMount fetches the registrations once. (CollectionEditForm's
366
+ // renderAdditionalContent also runs here, since the edited collection has
367
+ // an id, injecting the import/reap task panels into the form.)
368
+ expect(fetchLibraryRegistrations).toHaveBeenCalledTimes(1);
369
+
370
+ // Registering a library goes through getChildContext().registerLibrary.
371
+ expect(registerLibrary).not.toHaveBeenCalled();
372
+ await user.click(screen.getByRole("button", { name: "Register" }));
373
+
374
+ expect(registerLibrary).toHaveBeenCalledTimes(1);
375
+ const formData = registerLibrary.mock.calls[0][0];
376
+ expect(formData.get("library_short_name")).toBe("nypl");
377
+ expect(formData.get("collection_id")).toBe("7");
378
+
379
+ // After a successful registration, the child context refetches.
380
+ await waitFor(() =>
381
+ expect(fetchLibraryRegistrations).toHaveBeenCalledTimes(2)
382
+ );
383
+ });
384
+ });
385
+
386
+ describe("confirm before disassociating libraries", () => {
387
+ const initialLibraries = [
388
+ { short_name: "palace", name: "Palace" },
389
+ { short_name: "another-library", name: "Another Library" },
390
+ ];
391
+
392
+ const renderEditForm = (
393
+ libraries: Array<{ short_name: string }>,
394
+ libraryMeta: Array<{ short_name: string; name?: string }>
395
+ ) =>
396
+ renderWithContext(
397
+ <Collections
398
+ data={
399
+ {
400
+ collections: [
401
+ {
402
+ id: 7,
403
+ protocol: "OPDS Import",
404
+ name: "An OPDS Collection",
405
+ libraries,
406
+ },
407
+ ],
408
+ protocols: [
409
+ { name: "OPDS Import", settings: [], library_settings: [] },
410
+ ],
411
+ allLibraries: libraryMeta,
412
+ } as any
413
+ }
414
+ editOrCreate="edit"
415
+ identifier="7"
416
+ fetchData={jest.fn()}
417
+ editItem={jest.fn().mockResolvedValue(undefined)}
418
+ deleteItem={jest.fn().mockResolvedValue(undefined)}
419
+ registerLibrary={jest.fn().mockResolvedValue(undefined)}
420
+ importCollection={jest.fn().mockResolvedValue(undefined)}
421
+ reapCollection={jest.fn().mockResolvedValue(undefined)}
422
+ csrfToken="token"
423
+ isFetching={false}
424
+ />,
425
+ sysAdminConfig
426
+ );
427
+
428
+ it("removes the library when the confirmation is accepted", () => {
429
+ const confirmSpy = jest.spyOn(window, "confirm").mockReturnValue(true);
430
+ const { container } = renderEditForm(
431
+ [...initialLibraries],
432
+ [...initialLibraries]
433
+ );
434
+
435
+ // One remove button per associated library.
436
+ expect(container.querySelectorAll("button.remove-btn")).toHaveLength(2);
437
+
438
+ fireEvent.click(container.querySelectorAll("button.remove-btn")[0]);
439
+
440
+ // The prompt names the (full) library being removed.
441
+ expect(confirmSpy).toHaveBeenCalledTimes(1);
442
+ expect(confirmSpy.mock.calls[0][0]).toBe(
443
+ 'Disassociating library "Palace" from this collection will ' +
444
+ "remove all loans and holds for its patrons. Do you wish to continue?"
445
+ );
446
+
447
+ // The association (and its remove button) is gone.
448
+ expect(container.querySelectorAll("button.remove-btn")).toHaveLength(1);
449
+ });
450
+
451
+ it("keeps the library when the confirmation is canceled", () => {
452
+ jest.spyOn(window, "confirm").mockReturnValue(false);
453
+ const { container } = renderEditForm(
454
+ [...initialLibraries],
455
+ [...initialLibraries]
456
+ );
457
+
458
+ expect(container.querySelectorAll("button.remove-btn")).toHaveLength(2);
459
+ fireEvent.click(container.querySelectorAll("button.remove-btn")[0]);
460
+ // Nothing was removed.
461
+ expect(container.querySelectorAll("button.remove-btn")).toHaveLength(2);
462
+ });
463
+
464
+ it("uses the library short_name in the prompt when the full name is unavailable", () => {
465
+ const confirmSpy = jest.spyOn(window, "confirm").mockReturnValue(false);
466
+ // The library is not present in allLibraries, so getLibrary() returns null.
467
+ const { container } = renderEditForm([{ short_name: "orphan" }], []);
468
+
469
+ fireEvent.click(container.querySelector("button.remove-btn"));
470
+
471
+ expect(confirmSpy).toHaveBeenCalledTimes(1);
472
+ expect(confirmSpy.mock.calls[0][0]).toBe(
473
+ 'Disassociating library "orphan" from this collection will ' +
474
+ "remove all loans and holds for its patrons. Do you wish to continue?"
475
+ );
476
+ });
477
+ });
478
+
479
+ describe("create mode", () => {
480
+ it("renders the create form without import/reap task panels", () => {
481
+ // In create mode there is no saved collection, so CollectionEditForm's
482
+ // renderAdditionalContent short-circuits and injects no task panels.
483
+ renderWithContext(
484
+ <Collections
485
+ data={
486
+ {
487
+ collections: [],
488
+ protocols: [
489
+ { name: "OPDS Import", settings: [], library_settings: [] },
490
+ ],
491
+ allLibraries,
492
+ } as any
493
+ }
494
+ editOrCreate="create"
495
+ fetchData={jest.fn()}
496
+ editItem={jest.fn().mockResolvedValue(undefined)}
497
+ deleteItem={jest.fn().mockResolvedValue(undefined)}
498
+ registerLibrary={jest.fn().mockResolvedValue(undefined)}
499
+ importCollection={jest.fn().mockResolvedValue(undefined)}
500
+ reapCollection={jest.fn().mockResolvedValue(undefined)}
501
+ csrfToken="token"
502
+ isFetching={false}
503
+ />,
504
+ sysAdminConfig
505
+ );
506
+
507
+ expect(
508
+ screen.getByRole("heading", { name: "Create a new collection" })
509
+ ).toBeInTheDocument();
510
+ });
511
+ });
512
+
513
+ describe("deletion", () => {
514
+ it("deletes a collection and refetches after confirmation", async () => {
515
+ const deleteItem = jest.fn().mockResolvedValue(undefined);
516
+ const fetchData = jest.fn();
517
+ const confirmSpy = jest.spyOn(window, "confirm").mockReturnValue(true);
518
+
519
+ const { container } = renderWithContext(
520
+ <Collections
521
+ data={
522
+ {
523
+ collections: [{ id: 1, protocol: "p", name: "My Collection" }],
524
+ protocols: [],
525
+ allLibraries,
526
+ } as any
527
+ }
528
+ fetchData={fetchData}
529
+ editItem={jest.fn().mockResolvedValue(undefined)}
530
+ deleteItem={deleteItem}
531
+ registerLibrary={jest.fn().mockResolvedValue(undefined)}
532
+ importCollection={jest.fn().mockResolvedValue(undefined)}
533
+ reapCollection={jest.fn().mockResolvedValue(undefined)}
534
+ csrfToken="token"
535
+ isFetching={false}
536
+ />,
537
+ sysAdminConfig
538
+ );
539
+
540
+ fireEvent.click(container.querySelector("button.delete-item"));
541
+
542
+ expect(confirmSpy).toHaveBeenCalledTimes(1);
543
+ await waitFor(() => expect(deleteItem).toHaveBeenCalledWith(1));
544
+ // fetchData is called once on mount; the post-delete refetch is the second
545
+ // call, so assert the count rather than mere invocation.
546
+ await waitFor(() => expect(fetchData).toHaveBeenCalledTimes(2));
547
+ });
548
+ });
549
+ });
@@ -0,0 +1,157 @@
1
+ import * as React from "react";
2
+ import { render, screen, within } from "@testing-library/react";
3
+ import userEvent from "@testing-library/user-event";
4
+
5
+ import Contributors from "../../../src/components/Contributors";
6
+ import { RolesData, ContributorData } from "../../../src/interfaces";
7
+
8
+ const roles: RolesData = {
9
+ aut: "Author",
10
+ ill: "Illustrator",
11
+ nrt: "Narrator",
12
+ trl: "Translator",
13
+ };
14
+
15
+ const contributors: ContributorData[] = [
16
+ { name: "A Translator", role: "trl" },
17
+ { name: "A Narrator", role: "nrt" },
18
+ ];
19
+
20
+ const renderContributors = (
21
+ props: Partial<React.ComponentProps<typeof Contributors>> = {}
22
+ ) =>
23
+ render(
24
+ <Contributors
25
+ roles={roles}
26
+ contributors={contributors}
27
+ disabled={false}
28
+ {...props}
29
+ />
30
+ );
31
+
32
+ const existingRows = (container: HTMLElement) =>
33
+ Array.from(container.querySelectorAll<HTMLElement>(".with-remove-button"));
34
+
35
+ const newContributorForm = () =>
36
+ screen
37
+ .getByRole("button", { name: "Add" })
38
+ .closest(".contributor-form") as HTMLElement;
39
+
40
+ const roleSelect = (row: HTMLElement) =>
41
+ row.querySelector('select[name="contributor-role"]') as HTMLSelectElement;
42
+ const nameInput = (row: HTMLElement) =>
43
+ row.querySelector('input[name="contributor-name"]') as HTMLInputElement;
44
+
45
+ describe("Contributors", () => {
46
+ it("displays a label", () => {
47
+ renderContributors();
48
+ expect(screen.getByText("Authors and Contributors")).toBeInTheDocument();
49
+ });
50
+
51
+ it("displays a list of existing contributors", () => {
52
+ const { container } = renderContributors();
53
+ const rows = existingRows(container);
54
+ expect(rows).toHaveLength(2);
55
+
56
+ expect(roleSelect(rows[0])).toHaveValue("Translator");
57
+ expect(nameInput(rows[0])).toHaveValue("A Translator");
58
+ expect(roleSelect(rows[1])).toHaveValue("Narrator");
59
+ expect(nameInput(rows[1])).toHaveValue("A Narrator");
60
+
61
+ // Each role menu offers the full set of roles.
62
+ const options = within(roleSelect(rows[0]))
63
+ .getAllByRole("option")
64
+ .map((o) => (o as HTMLOptionElement).value);
65
+ expect(options).toStrictEqual(Object.values(roles));
66
+ });
67
+
68
+ it("displays a blank field for adding a new contributor", () => {
69
+ renderContributors();
70
+ const form = newContributorForm();
71
+ expect(roleSelect(form)).toHaveValue("Author");
72
+ expect(nameInput(form)).toHaveValue("");
73
+
74
+ const button = within(form).getByRole("button", { name: "Add" });
75
+ expect(button).toHaveClass("add-contributor");
76
+ });
77
+
78
+ it("deletes a contributor", async () => {
79
+ const user = userEvent.setup();
80
+ const { container } = renderContributors();
81
+
82
+ let rows = existingRows(container);
83
+ expect(rows).toHaveLength(2);
84
+
85
+ // Remove the first (Translator) row.
86
+ await user.click(within(rows[0]).getByRole("button"));
87
+
88
+ rows = existingRows(container);
89
+ expect(rows).toHaveLength(1);
90
+ expect(roleSelect(rows[0])).toHaveValue("Narrator");
91
+ expect(nameInput(rows[0])).toHaveValue("A Narrator");
92
+ });
93
+
94
+ it("adds a contributor", async () => {
95
+ const user = userEvent.setup();
96
+ const { container } = renderContributors();
97
+ expect(existingRows(container)).toHaveLength(2);
98
+
99
+ const form = newContributorForm();
100
+ await user.selectOptions(roleSelect(form), "Illustrator");
101
+ await user.type(nameInput(form), "An Illustrator");
102
+ await user.click(within(form).getByRole("button", { name: "Add" }));
103
+
104
+ const rows = existingRows(container);
105
+ expect(rows).toHaveLength(3);
106
+ expect(roleSelect(rows[2])).toHaveValue("Illustrator");
107
+ expect(nameInput(rows[2])).toHaveValue("An Illustrator");
108
+ });
109
+
110
+ it("does not add an empty string as a contributor's name", async () => {
111
+ const user = userEvent.setup();
112
+ const { container } = renderContributors();
113
+
114
+ // The Add button starts disabled, so clicking it does nothing.
115
+ expect(screen.getByRole("button", { name: "Add" })).toBeDisabled();
116
+ await user.click(screen.getByRole("button", { name: "Add" }));
117
+ expect(existingRows(container)).toHaveLength(2);
118
+
119
+ // Typing a name enables the button and lets us add.
120
+ await user.type(nameInput(newContributorForm()), "An Author");
121
+ expect(screen.getByRole("button", { name: "Add" })).toBeEnabled();
122
+ await user.click(screen.getByRole("button", { name: "Add" }));
123
+ expect(existingRows(container)).toHaveLength(3);
124
+
125
+ // Clearing the name disables the button again.
126
+ await user.clear(nameInput(newContributorForm()));
127
+ expect(screen.getByRole("button", { name: "Add" })).toBeDisabled();
128
+ await user.click(screen.getByRole("button", { name: "Add" }));
129
+ expect(existingRows(container)).toHaveLength(3);
130
+ });
131
+
132
+ it("shows the full name of a contributor's known role", () => {
133
+ // "trl" and "nrt" resolve to their full names in the role menus.
134
+ const { container } = renderContributors();
135
+ const rows = existingRows(container);
136
+ expect(roleSelect(rows[0])).toHaveValue("Translator");
137
+ expect(roleSelect(rows[1])).toHaveValue("Narrator");
138
+ });
139
+
140
+ it("resets the form after adding a contributor", async () => {
141
+ const user = userEvent.setup();
142
+ renderContributors();
143
+
144
+ const form = newContributorForm();
145
+ await user.selectOptions(roleSelect(form), "Illustrator");
146
+ await user.type(nameInput(form), "An Illustrator");
147
+ await user.click(within(form).getByRole("button", { name: "Add" }));
148
+
149
+ // The add form is blank again, defaulted to "Author", with a disabled button.
150
+ const resetForm = newContributorForm();
151
+ expect(nameInput(resetForm)).toHaveValue("");
152
+ expect(roleSelect(resetForm)).toHaveValue("Author");
153
+ expect(
154
+ within(resetForm).getByRole("button", { name: "Add" })
155
+ ).toBeDisabled();
156
+ });
157
+ });