SpreadsheetPreviewModal.test.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. /**
  2. * Tests for SpreadsheetPreviewModal (#2976).
  3. *
  4. * CSV parsing uses the real papaparse and XLSX parsing the real SheetJS —
  5. * only the network fetch is stubbed, so the tests cover the actual parse
  6. * paths the preview relies on.
  7. */
  8. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
  9. import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
  10. import userEvent from '@testing-library/user-event';
  11. import * as XLSX from 'xlsx';
  12. import { SpreadsheetPreviewModal } from '../../components/SpreadsheetPreviewModal';
  13. vi.mock('../../api/client', () => ({
  14. api: {
  15. getLibraryFileDownloadUrl: vi.fn((id: number) => `http://test/library/files/${id}/download`),
  16. },
  17. getAuthToken: () => null,
  18. }));
  19. const mockOnClose = vi.fn();
  20. function stubFetchWith(bytes: ArrayBuffer | Uint8Array | string) {
  21. const body = typeof bytes === 'string' ? new TextEncoder().encode(bytes) : bytes;
  22. vi.stubGlobal(
  23. 'fetch',
  24. vi.fn(async () => new Response(body as BodyInit, { status: 200 })),
  25. );
  26. }
  27. function renderModal(props: Partial<Parameters<typeof SpreadsheetPreviewModal>[0]> = {}) {
  28. return render(
  29. <SpreadsheetPreviewModal
  30. libraryFileId={42}
  31. filename="parts.csv"
  32. fileType="csv"
  33. fileSize={1234}
  34. onClose={mockOnClose}
  35. {...props}
  36. />,
  37. );
  38. }
  39. describe('SpreadsheetPreviewModal', () => {
  40. beforeEach(() => {
  41. vi.clearAllMocks();
  42. });
  43. afterEach(() => {
  44. vi.unstubAllGlobals();
  45. });
  46. it('renders CSV cells as a read-only grid', async () => {
  47. stubFetchWith('Article,Qty\nM3 screw,12\nBearing 608,4\n');
  48. renderModal();
  49. expect(await screen.findByText('M3 screw')).toBeInTheDocument();
  50. expect(screen.getByText('Bearing 608')).toBeInTheDocument();
  51. expect(screen.getByText('Qty')).toBeInTheDocument();
  52. });
  53. it('shows a truncation notice for long CSV files', async () => {
  54. const rows = Array.from({ length: 600 }, (_, i) => `row${i},${i}`).join('\n');
  55. stubFetchWith(`name,value\n${rows}\n`);
  56. renderModal();
  57. expect(await screen.findByText('row0')).toBeInTheDocument();
  58. expect(screen.getByText(/Showing the first/)).toBeInTheDocument();
  59. expect(screen.queryByText('row599')).not.toBeInTheDocument();
  60. });
  61. it('renders XLSX workbooks with one tab per sheet', async () => {
  62. const workbook = XLSX.utils.book_new();
  63. XLSX.utils.book_append_sheet(
  64. workbook,
  65. XLSX.utils.aoa_to_sheet([
  66. ['Part', 'Price'],
  67. ['Nozzle', '12.50'],
  68. ]),
  69. 'Parts',
  70. );
  71. XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([['SupplierList']]), 'Suppliers');
  72. const bytes = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' }) as ArrayBuffer;
  73. stubFetchWith(bytes);
  74. const user = userEvent.setup();
  75. renderModal({ filename: 'bom.xlsx', fileType: 'xlsx' });
  76. expect(await screen.findByText('Nozzle')).toBeInTheDocument();
  77. // Both sheets appear as tabs; switching shows the second sheet's content.
  78. await user.click(screen.getByRole('button', { name: 'Suppliers' }));
  79. expect(await screen.findByText('SupplierList')).toBeInTheDocument();
  80. expect(screen.queryByText('Nozzle')).not.toBeInTheDocument();
  81. });
  82. it('shows an error message for a broken workbook', async () => {
  83. // A truncated ZIP: SheetJS recognises the PK magic, then fails to parse.
  84. // (Plain text bytes would be leniently read as CSV, not rejected.)
  85. stubFetchWith(new Uint8Array([0x50, 0x4b, 0x03, 0x04, 0x01, 0x02, 0x03]));
  86. renderModal({ filename: 'broken.xlsx', fileType: 'xlsx' });
  87. expect(await screen.findByText('This file cannot be previewed.')).toBeInTheDocument();
  88. });
  89. it('refuses oversized files without fetching them', async () => {
  90. const fetchSpy = vi.fn();
  91. vi.stubGlobal('fetch', fetchSpy);
  92. renderModal({ fileSize: 100 * 1024 * 1024 });
  93. expect(await screen.findByText(/too large to preview/)).toBeInTheDocument();
  94. expect(fetchSpy).not.toHaveBeenCalled();
  95. });
  96. describe('fullscreen', () => {
  97. const requestFullscreen = vi.fn();
  98. const exitFullscreen = vi.fn();
  99. beforeEach(() => {
  100. requestFullscreen.mockReset().mockResolvedValue(undefined);
  101. exitFullscreen.mockReset().mockResolvedValue(undefined);
  102. Object.defineProperty(document, 'fullscreenEnabled', { configurable: true, value: true });
  103. Object.defineProperty(document, 'fullscreenElement', { configurable: true, value: null, writable: true });
  104. Object.defineProperty(document, 'exitFullscreen', { configurable: true, value: exitFullscreen });
  105. Object.defineProperty(HTMLElement.prototype, 'requestFullscreen', { configurable: true, value: requestFullscreen });
  106. });
  107. afterEach(() => {
  108. delete (document as { fullscreenEnabled?: boolean }).fullscreenEnabled;
  109. delete (document as { fullscreenElement?: Element | null }).fullscreenElement;
  110. delete (document as { exitFullscreen?: () => Promise<void> }).exitFullscreen;
  111. delete (HTMLElement.prototype as { requestFullscreen?: () => Promise<void> }).requestFullscreen;
  112. });
  113. it('double-click on the sheet toggles fullscreen', async () => {
  114. stubFetchWith('Article,Qty\nM3 screw,12\n');
  115. renderModal();
  116. await screen.findByText('M3 screw');
  117. const content = screen.getByTestId('spreadsheet-preview-content');
  118. const panel = screen.getByText('parts.csv').closest('.flex-col') as HTMLElement;
  119. fireEvent.doubleClick(content);
  120. expect(requestFullscreen).toHaveBeenCalledTimes(1);
  121. expect(requestFullscreen.mock.instances[0]).toBe(panel);
  122. // The mocks do not flip fullscreenElement or fire fullscreenchange;
  123. // play the browser's part.
  124. (document as { fullscreenElement: Element | null }).fullscreenElement = panel;
  125. act(() => {
  126. document.dispatchEvent(new Event('fullscreenchange'));
  127. });
  128. expect(screen.getByRole('button', { name: 'Exit fullscreen' })).toBeInTheDocument();
  129. fireEvent.doubleClick(content);
  130. expect(exitFullscreen).toHaveBeenCalledTimes(1);
  131. });
  132. it('offers a fullscreen button in the header', async () => {
  133. stubFetchWith('Article,Qty\nM3 screw,12\n');
  134. const user = userEvent.setup();
  135. renderModal();
  136. await screen.findByText('M3 screw');
  137. await user.click(screen.getByRole('button', { name: 'Fullscreen' }));
  138. expect(requestFullscreen).toHaveBeenCalledTimes(1);
  139. });
  140. });
  141. describe('grid thumbnail snapshot', () => {
  142. // The snapshot is drawn into an offscreen canvas, which jsdom cannot
  143. // back: both the 2D context and toBlob are stood in for.
  144. function stubCanvas2d(blob: Blob | null = new Blob(['png'], { type: 'image/png' })) {
  145. const context = {
  146. fillStyle: '',
  147. strokeStyle: '',
  148. lineWidth: 0,
  149. font: '',
  150. textBaseline: '',
  151. fillRect: vi.fn(),
  152. beginPath: vi.fn(),
  153. moveTo: vi.fn(),
  154. lineTo: vi.fn(),
  155. stroke: vi.fn(),
  156. fillText: vi.fn(),
  157. };
  158. vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(
  159. context as unknown as CanvasRenderingContext2D,
  160. );
  161. vi.spyOn(HTMLCanvasElement.prototype, 'toBlob').mockImplementation((callback) => callback(blob));
  162. return context;
  163. }
  164. afterEach(() => {
  165. vi.restoreAllMocks();
  166. });
  167. it('hands the first sheet to onSnapshot as a PNG', async () => {
  168. const context = stubCanvas2d();
  169. stubFetchWith('Article,Qty\nM3 screw,12\n');
  170. const onSnapshot = vi.fn();
  171. renderModal({ onSnapshot });
  172. await screen.findByText('M3 screw');
  173. await waitFor(() => expect(onSnapshot).toHaveBeenCalledTimes(1));
  174. expect((onSnapshot.mock.calls[0][0] as Blob).type).toBe('image/png');
  175. // The mini table is what makes it recognisable in the grid.
  176. expect(context.fillText).toHaveBeenCalledWith('M3 screw', expect.any(Number), expect.any(Number), expect.any(Number));
  177. });
  178. it('draws the first sheet that has rows, not an empty leading one', async () => {
  179. stubCanvas2d();
  180. const workbook = XLSX.utils.book_new();
  181. XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([]), 'Cover');
  182. XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([['Part', 'Qty'], ['Hinge', '2']]), 'Bom');
  183. stubFetchWith(XLSX.write(workbook, { type: 'array', bookType: 'xlsx' }) as ArrayBuffer);
  184. const onSnapshot = vi.fn();
  185. renderModal({ onSnapshot, filename: 'bom.xlsx', fileType: 'xlsx' });
  186. // The empty Cover sheet opens first, so the tab strip is what says the
  187. // workbook has parsed.
  188. await screen.findByRole('button', { name: 'Bom' });
  189. await waitFor(() => expect(onSnapshot).toHaveBeenCalledTimes(1));
  190. });
  191. it('stays quiet for a sheet with no rows at all', async () => {
  192. stubCanvas2d();
  193. stubFetchWith('');
  194. const onSnapshot = vi.fn();
  195. renderModal({ onSnapshot });
  196. await screen.findByText('This sheet is empty');
  197. expect(onSnapshot).not.toHaveBeenCalled();
  198. });
  199. });
  200. });