SupplierSection.test.tsx 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. /**
  2. * Tests for the spool dialog's supplier multi-select (#2988).
  3. */
  4. import { useState } from 'react';
  5. import { describe, it, expect, vi, beforeEach } from 'vitest';
  6. import { render, screen, waitFor } from '@testing-library/react';
  7. import userEvent from '@testing-library/user-event';
  8. import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  9. import { SupplierSection, type SupplierLinkDraft } from '../../components/spool-form/SupplierSection';
  10. import { api } from '../../api/client';
  11. import { inventorySuppliersQueryKey } from '../../utils/inventoryQueries';
  12. const mockShowToast = vi.fn();
  13. vi.mock('../../api/client', () => ({
  14. api: {
  15. getSuppliers: vi.fn(),
  16. createSupplier: vi.fn(),
  17. },
  18. }));
  19. vi.mock('../../contexts/ToastContext', () => ({
  20. useToast: () => ({ showToast: mockShowToast }),
  21. }));
  22. const suppliers = [
  23. { id: 1, name: 'Filament24', website: null, customer_number: null, note: null, spool_count: 0, created_at: '', updated_at: '' },
  24. { id: 2, name: 'PrintStore', website: null, customer_number: null, note: null, spool_count: 0, created_at: '', updated_at: '' },
  25. ];
  26. function Harness({ initial = [] as SupplierLinkDraft[], onChange = (_: SupplierLinkDraft[]) => {} }) {
  27. const [links, setLinks] = useState<SupplierLinkDraft[]>(initial);
  28. return (
  29. <SupplierSection
  30. links={links}
  31. onChange={(next) => {
  32. setLinks(next);
  33. onChange(next);
  34. }}
  35. currencySymbol="€"
  36. />
  37. );
  38. }
  39. // The supplier list is read through react-query under the shared
  40. // inventory-suppliers key, so every render needs a client (#2988).
  41. function renderSection(ui: React.ReactElement) {
  42. const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  43. return { ...render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>), client };
  44. }
  45. describe('SupplierSection', () => {
  46. beforeEach(() => {
  47. vi.clearAllMocks();
  48. (api.getSuppliers as ReturnType<typeof vi.fn>).mockResolvedValue(suppliers);
  49. });
  50. it('adds a supplier from the dropdown as a chip', async () => {
  51. const onChange = vi.fn();
  52. const user = userEvent.setup();
  53. renderSection(<Harness onChange={onChange} />);
  54. await user.click(screen.getByRole('button', { name: /Add supplier/ }));
  55. await user.click(await screen.findByRole('button', { name: 'Filament24' }));
  56. expect(screen.getByText('Filament24')).toBeInTheDocument();
  57. expect(onChange).toHaveBeenCalledWith([
  58. expect.objectContaining({ supplier_id: 1, supplier_name: 'Filament24', is_purchase_source: false }),
  59. ]);
  60. });
  61. it('creates a new supplier inline without leaving the dialog', async () => {
  62. (api.createSupplier as ReturnType<typeof vi.fn>).mockResolvedValue({
  63. id: 3, name: 'NewShop', website: null, customer_number: null, note: null, spool_count: 0, created_at: '', updated_at: '',
  64. });
  65. const user = userEvent.setup();
  66. renderSection(<Harness />);
  67. await user.click(screen.getByRole('button', { name: /Add supplier/ }));
  68. await user.type(await screen.findByPlaceholderText(/Search suppliers/), 'NewShop');
  69. await user.click(screen.getByRole('button', { name: /Create "NewShop"/ }));
  70. await waitFor(() => {
  71. expect(api.createSupplier).toHaveBeenCalledWith({ name: 'NewShop' });
  72. });
  73. expect(screen.getByText('NewShop')).toBeInTheDocument();
  74. });
  75. it('says the load failed instead of offering an empty list', async () => {
  76. // Silently rendering nothing invites the user to create a supplier that
  77. // already exists.
  78. (api.getSuppliers as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('boom'));
  79. const user = userEvent.setup();
  80. renderSection(<Harness />);
  81. await user.click(screen.getByRole('button', { name: /Add supplier/ }));
  82. expect(await screen.findByText(/Failed to load suppliers/i)).toBeInTheDocument();
  83. });
  84. it('re-reads the list when the shared key is invalidated', async () => {
  85. const user = userEvent.setup();
  86. const { client } = renderSection(<Harness />);
  87. await user.click(screen.getByRole('button', { name: /Add supplier/ }));
  88. await screen.findByRole('button', { name: 'Filament24' });
  89. (api.getSuppliers as ReturnType<typeof vi.fn>).mockResolvedValue([
  90. ...suppliers,
  91. { id: 9, name: 'Elsewhere', website: null, customer_number: null, note: null, spool_count: 0, created_at: '', updated_at: '' },
  92. ]);
  93. await client.invalidateQueries({ queryKey: inventorySuppliersQueryKey });
  94. expect(await screen.findByRole('button', { name: 'Elsewhere' })).toBeInTheDocument();
  95. });
  96. it('keeps at most one purchase source across assignments', async () => {
  97. const onChange = vi.fn();
  98. const user = userEvent.setup();
  99. renderSection(
  100. <Harness
  101. initial={[
  102. { supplier_id: 1, supplier_name: 'Filament24', supplier_article_number: '', quoted_price_per_kg: null, is_purchase_source: true },
  103. { supplier_id: 2, supplier_name: 'PrintStore', supplier_article_number: '', quoted_price_per_kg: null, is_purchase_source: false },
  104. ]}
  105. onChange={onChange}
  106. />,
  107. );
  108. const checkboxes = screen.getAllByRole('checkbox');
  109. await user.click(checkboxes[1]);
  110. const last = onChange.mock.calls.at(-1)?.[0] as SupplierLinkDraft[];
  111. expect(last.find((l) => l.supplier_id === 2)?.is_purchase_source).toBe(true);
  112. // The previous purchase source was demoted automatically.
  113. expect(last.find((l) => l.supplier_id === 1)?.is_purchase_source).toBe(false);
  114. });
  115. it('removes an assignment via the chip', async () => {
  116. const onChange = vi.fn();
  117. const user = userEvent.setup();
  118. renderSection(
  119. <Harness
  120. initial={[
  121. { supplier_id: 1, supplier_name: 'Filament24', supplier_article_number: '', quoted_price_per_kg: null, is_purchase_source: false },
  122. ]}
  123. onChange={onChange}
  124. />,
  125. );
  126. await user.click(screen.getByRole('button', { name: /Remove/i }));
  127. expect(onChange).toHaveBeenLastCalledWith([]);
  128. expect(screen.queryByText('Filament24')).not.toBeInTheDocument();
  129. });
  130. });