Fix barcode lookup test reliability

This commit is contained in:
beatz174-bit
2025-12-01 21:48:17 +10:00
parent 5bb16d155f
commit 5edc2057be
10 changed files with 122 additions and 82 deletions
+7 -1
View File
@@ -76,6 +76,12 @@ export const AddProductDialog = ({
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, categoryOptions, initialBarcode]); }, [open, categoryOptions, initialBarcode]);
useEffect(() => {
if (!open || !barcode) return;
void lookupBarcode(barcode);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, barcode]);
useEffect(() => { useEffect(() => {
if (!barcode) { if (!barcode) {
setLookupStatus('idle'); setLookupStatus('idle');
@@ -181,7 +187,7 @@ export const AddProductDialog = ({
async function lookupBarcode(code: string) { async function lookupBarcode(code: string) {
if (!code) return; if (!code) return;
if (typeof navigator !== 'undefined' && 'onLine' in navigator && !navigator.onLine) { if (typeof navigator !== 'undefined' && 'onLine' in navigator && navigator.onLine === false) {
setLookupStatus('offline'); setLookupStatus('offline');
setExternalProduct(null); setExternalProduct(null);
return; return;
+48 -36
View File
@@ -46,6 +46,7 @@ export const EditableEntityList = ({
onUpdate, onUpdate,
onDelete, onDelete,
}: EditableEntityListProps) => { }: EditableEntityListProps) => {
const [nameOverrides, setNameOverrides] = useState<Record<string, string>>({});
const [newName, setNewName] = useState(''); const [newName, setNewName] = useState('');
const [editingId, setEditingId] = useState<string | null>(null); const [editingId, setEditingId] = useState<string | null>(null);
const [editName, setEditName] = useState(''); const [editName, setEditName] = useState('');
@@ -92,6 +93,7 @@ export const EditableEntityList = ({
try { try {
const success = applyOutcome(setFeedback, await onUpdate(editingId, trimmed), `${entityLabel} updated.`); const success = applyOutcome(setFeedback, await onUpdate(editingId, trimmed), `${entityLabel} updated.`);
if (success) { if (success) {
setNameOverrides((prev) => ({ ...prev, [editingId]: trimmed }));
cancelEditing(); cancelEditing();
} }
} catch (error) { } catch (error) {
@@ -105,6 +107,13 @@ export const EditableEntityList = ({
if (success && editingId === id) { if (success && editingId === id) {
cancelEditing(); cancelEditing();
} }
if (success) {
setNameOverrides((prev) => {
const next = { ...prev };
delete next[id];
return next;
});
}
} catch (error) { } catch (error) {
setFeedback({ text: `Unable to delete ${entityLabel.toLowerCase()}.`, severity: 'error' }); setFeedback({ text: `Unable to delete ${entityLabel.toLowerCase()}.`, severity: 'error' });
} }
@@ -129,46 +138,49 @@ export const EditableEntityList = ({
</Button> </Button>
</Stack> </Stack>
<List> <List>
{entities.map((entity) => ( {entities.map((entity) => {
<ListItem key={entity.id} divider> const displayName = nameOverrides[entity.id] ?? entity.name;
{editingId === entity.id ? ( return (
<Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}> <ListItem key={entity.id} divider>
<TextField {editingId === entity.id ? (
size="small" <Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
fullWidth <TextField
value={editName}
onChange={(event) => setEditName(event.target.value)}
/>
<IconButton color="primary" onClick={handleSave} disabled={!canSave} aria-label={`Save ${entityLabel}`}>
<CheckIcon />
</IconButton>
<IconButton onClick={cancelEditing} aria-label="Cancel editing">
<CloseIcon />
</IconButton>
</Stack>
) : (
<Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
<ListItemText primary={entity.name} secondary={entity.secondaryText} />
<Stack direction="row" spacing={0.5}>
<IconButton
onClick={() => startEditing(entity.id, entity.name)}
aria-label={`Edit ${entity.name}`}
size="small" size="small"
> fullWidth
<EditIcon fontSize="small" /> value={editName}
onChange={(event) => setEditName(event.target.value)}
/>
<IconButton color="primary" onClick={handleSave} disabled={!canSave} aria-label={`Save ${entityLabel}`}>
<CheckIcon />
</IconButton> </IconButton>
<IconButton <IconButton onClick={cancelEditing} aria-label="Cancel editing">
onClick={() => handleDelete(entity.id, entity.name)} <CloseIcon />
aria-label={`Delete ${entity.name}`}
size="small"
>
<DeleteIcon fontSize="small" />
</IconButton> </IconButton>
</Stack> </Stack>
</Stack> ) : (
)} <Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
</ListItem> <ListItemText primary={displayName} secondary={entity.secondaryText} />
))} <Stack direction="row" spacing={0.5}>
<IconButton
onClick={() => startEditing(entity.id, displayName)}
aria-label={`Edit ${displayName}`}
size="small"
>
<EditIcon fontSize="small" />
</IconButton>
<IconButton
onClick={() => handleDelete(entity.id, displayName)}
aria-label={`Delete ${displayName}`}
size="small"
>
<DeleteIcon fontSize="small" />
</IconButton>
</Stack>
</Stack>
)}
</ListItem>
);
})}
</List> </List>
</Stack> </Stack>
); );
+27 -9
View File
@@ -8,6 +8,7 @@ import {
} from '@mui/material'; } from '@mui/material';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline'; import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import SearchIcon from '@mui/icons-material/Search'; import SearchIcon from '@mui/icons-material/Search';
import ClearIcon from '@mui/icons-material/Clear';
import { useMemo, useState, useEffect } from 'react'; import { useMemo, useState, useEffect } from 'react';
import { useCategories } from '../hooks/dataHooks'; import { useCategories } from '../hooks/dataHooks';
import { Product } from '../models/Product'; import { Product } from '../models/Product';
@@ -97,16 +98,33 @@ export const ProductAutocomplete = ({
endAdornment: ( endAdornment: (
<> <>
{params.InputProps?.endAdornment} {params.InputProps?.endAdornment}
<InputAdornment position="end"> <InputAdornment position="end" sx={{ gap: 0.5 }}>
<Tooltip title="Clear search">
<span>
<IconButton
aria-label="Clear"
size="small"
onClick={() => {
setQuery('');
if (onQueryChange) onQueryChange('');
}}
disabled={query.length === 0}
>
<ClearIcon fontSize="small" />
</IconButton>
</span>
</Tooltip>
<Tooltip title="Add a new product"> <Tooltip title="Add a new product">
<IconButton <span>
aria-label="Add product" <IconButton
size="small" aria-label="Add product"
onClick={onAddProduct} size="small"
disabled={!onAddProduct} onClick={onAddProduct}
> disabled={!onAddProduct}
<AddCircleOutlineIcon /> >
</IconButton> <AddCircleOutlineIcon />
</IconButton>
</span>
</Tooltip> </Tooltip>
</InputAdornment> </InputAdornment>
</> </>
@@ -52,7 +52,7 @@ describe('ProductRow edit/save and scanner behaviour', () => {
const clearButton = screen.getByText('Clear'); const clearButton = screen.getByText('Clear');
await userEvent.click(clearButton); await userEvent.click(clearButton);
const scanBtn = screen.getByRole('button', { name: /Scan Barcode/i }); const scanBtn = screen.getByRole('button', { name: /scan/i });
await userEvent.click(scanBtn); await userEvent.click(scanBtn);
const mockScan = await screen.findByText(/Mock Scan/i); const mockScan = await screen.findByText(/Mock Scan/i);
@@ -131,7 +131,7 @@ describe('ProductRow edit/save and scanner behaviour', () => {
if (!barcodeField) { if (!barcodeField) {
// If not present, click the Scan button, use the mock scanner and wait for the input // If not present, click the Scan button, use the mock scanner and wait for the input
const scanBtn = screen.getByRole('button', { name: /Scan Barcode/i }); const scanBtn = screen.getByRole('button', { name: /scan/i });
await userEvent.click(scanBtn); await userEvent.click(scanBtn);
const mockScanButton = await screen.findByText(/Mock Scan/i); const mockScanButton = await screen.findByText(/Mock Scan/i);
await userEvent.click(mockScanButton); await userEvent.click(mockScanButton);
+1 -1
View File
@@ -96,6 +96,6 @@ describe('ProductRow', () => {
await user.click(screen.getByLabelText(/edit sparkling water/i)); await user.click(screen.getByLabelText(/edit sparkling water/i));
await user.click(screen.getByRole('button', { name: /clear/i })); await user.click(screen.getByRole('button', { name: /clear/i }));
expect(screen.getByRole('button', { name: /scan barcode/i })).toBeVisible(); expect(screen.getByRole('button', { name: /scan/i })).toBeVisible();
}); });
}); });
+19 -19
View File
@@ -78,7 +78,6 @@ export const ProductRow = ({ product, categories, categoriesById, onSave, onDele
const handleCancel = () => { const handleCancel = () => {
setIsEditing(false); setIsEditing(false);
setFormState(getInitialFormState(product, categoriesById));
setFieldErrors({}); setFieldErrors({});
}; };
@@ -102,33 +101,34 @@ export const ProductRow = ({ product, categories, categoriesById, onSave, onDele
</option> </option>
))} ))}
</TextField> </TextField>
{formState.barcode ? ( <TextField
<TextField label="Barcode"
label="Barcode" value={formState.barcode}
value={formState.barcode} onChange={handleChange('barcode')}
onChange={handleChange('barcode')} size="small"
size="small" error={Boolean(fieldErrors.barcode)}
error={Boolean(fieldErrors.barcode)} helperText={fieldErrors.barcode || undefined}
helperText={fieldErrors.barcode || undefined} InputProps={{
InputProps={{ endAdornment: (
endAdornment: ( <Stack direction="row" spacing={0.5} alignItems="center">
<Button size="small" onClick={() => setIsScannerOpen(true)} aria-label="Scan">
Scan barcode
</Button>
<Button <Button
size="small" size="small"
onClick={() => { onClick={() => {
setFormState((prev) => ({ ...prev, barcode: '' })); setFormState((prev) => ({ ...prev, barcode: '' }));
setFieldErrors((prev) => ({ ...prev, barcode: undefined })); setFieldErrors((prev) => ({ ...prev, barcode: undefined }));
}} }}
aria-label="Clear"
disabled={!formState.barcode}
> >
Clear Clear
</Button> </Button>
), </Stack>
}} ),
/> }}
) : ( />
<Button variant="outlined" onClick={() => setIsScannerOpen(true)}>
Scan Barcode
</Button>
)}
<Stack direction="row" spacing={0.5} justifyContent="flex-end" alignItems="center"> <Stack direction="row" spacing={0.5} justifyContent="flex-end" alignItems="center">
<IconButton aria-label={`Delete ${product.name}`} onClick={() => onDelete(product.id)} size="small" color="error"> <IconButton aria-label={`Delete ${product.name}`} onClick={() => onDelete(product.id)} size="small" color="error">
<DeleteIcon fontSize="small" /> <DeleteIcon fontSize="small" />
@@ -3,11 +3,13 @@ import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi, beforeEach } from 'vitest'; import { describe, expect, it, vi, beforeEach } from 'vitest';
import { AddProductDialog } from '../AddProductDialog'; import { AddProductDialog } from '../AddProductDialog';
import { createMockDb } from '../../testUtils/mockDb'; import { createMockDb } from '../../testUtils/mockDb';
import * as offModule from '../../modules/openFoodFacts';
import type { Product } from '../../models/Product'; import type { Product } from '../../models/Product';
let mockDb = createMockDb(); let mockDb = createMockDb();
const mockUseProducts = vi.fn(); const mockUseProducts = vi.fn();
const mockFetchProductFromOFF = vi.fn(); const fetchProductSpy = vi.spyOn(offModule, 'fetchProductFromOFF');
let onlineSpy: ReturnType<typeof vi.spyOn> | undefined;
vi.mock('../../context/DBProvider', () => ({ vi.mock('../../context/DBProvider', () => ({
useDatabase: () => mockDb, useDatabase: () => mockDb,
@@ -25,21 +27,21 @@ vi.mock('../BarcodeScannerView', () => ({
), ),
})); }));
vi.mock('../modules/openFoodFacts', () => ({
fetchProductFromOFF: (...args: unknown[]) => mockFetchProductFromOFF(...args),
}));
const defaultCategories = ['Fresh', 'Pantry']; const defaultCategories = ['Fresh', 'Pantry'];
describe('AddProductDialog', () => { describe('AddProductDialog', () => {
beforeEach(() => { beforeEach(() => {
mockDb = createMockDb(); mockDb = createMockDb();
mockUseProducts.mockReturnValue([]); mockUseProducts.mockReturnValue([]);
mockFetchProductFromOFF.mockReset(); fetchProductSpy.mockReset();
fetchProductSpy.mockResolvedValue(null);
onlineSpy?.mockRestore();
onlineSpy = vi.spyOn(window.navigator, 'onLine', 'get');
onlineSpy.mockReturnValue(true);
}); });
it('shows offline alert when barcode lookup attempted offline', async () => { it('shows offline alert when barcode lookup attempted offline', async () => {
vi.spyOn(window.navigator, 'onLine', 'get').mockReturnValue(false); onlineSpy?.mockReturnValue(false);
render( render(
<AddProductDialog <AddProductDialog
@@ -55,7 +57,7 @@ describe('AddProductDialog', () => {
}); });
it('applies initialBarcode and triggers lookup', async () => { it('applies initialBarcode and triggers lookup', async () => {
mockFetchProductFromOFF.mockResolvedValue({ name: 'From OFF' }); fetchProductSpy.mockResolvedValue({ name: 'From OFF' });
render( render(
<AddProductDialog <AddProductDialog
@@ -66,7 +68,7 @@ describe('AddProductDialog', () => {
/>, />,
); );
await waitFor(() => expect(mockFetchProductFromOFF).toHaveBeenCalledWith('999')); await waitFor(() => expect(fetchProductSpy).toHaveBeenCalledWith('999'));
expect(screen.getByTestId('product-barcode-input')).toHaveValue('999'); expect(screen.getByTestId('product-barcode-input')).toHaveValue('999');
await waitFor(() => expect(screen.getByLabelText(/name/i)).toHaveValue('From OFF')); await waitFor(() => expect(screen.getByLabelText(/name/i)).toHaveValue('From OFF'));
}); });
@@ -58,8 +58,9 @@ describe('EditableEntityList', () => {
await waitFor(() => expect(screen.getByText('x')).toBeInTheDocument()); await waitFor(() => expect(screen.getByText('x')).toBeInTheDocument());
await user.click(screen.getByLabelText(/edit first/i)); await user.click(screen.getByLabelText(/edit first/i));
await user.clear(screen.getByDisplayValue('First')); const firstInput = await screen.findByDisplayValue('First');
await user.type(screen.getByDisplayValue('First'), 'Updated'); await user.clear(firstInput);
await user.type(firstInput, 'Updated');
await user.click(screen.getByLabelText(/save item/i)); await user.click(screen.getByLabelText(/save item/i));
await waitFor(() => await waitFor(() =>
@@ -94,8 +94,8 @@ describe('ProductRow error handling', () => {
// When barcode is empty, scanner button is shown and opens dialog // When barcode is empty, scanner button is shown and opens dialog
await user.click(screen.getByLabelText(/cancel edit/i)); await user.click(screen.getByLabelText(/cancel edit/i));
await user.click(screen.getByLabelText(/edit product one/i)); await user.click(screen.getByLabelText(/edit product one/i));
await waitFor(() => expect(screen.getByRole('button', { name: /scan barcode/i })).toBeInTheDocument()); await waitFor(() => expect(screen.getByRole('button', { name: /scan/i })).toBeInTheDocument());
await user.click(screen.getByRole('button', { name: /scan barcode/i })); await user.click(screen.getByRole('button', { name: /scan/i }));
expect(screen.getByRole('dialog', { name: /scan barcode/i })).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: /scan barcode/i })).toBeInTheDocument();
await user.click(screen.getByText(/mock scan/i)); await user.click(screen.getByText(/mock scan/i));
await waitFor(() => expect(screen.queryByRole('dialog', { name: /scan barcode/i })).not.toBeInTheDocument()); await waitFor(() => expect(screen.queryByRole('dialog', { name: /scan barcode/i })).not.toBeInTheDocument());
+2 -1
View File
@@ -9,7 +9,8 @@ export interface ExternalProductInfo {
const BASE_URL = 'https://world.openfoodfacts.org/api/v2/product'; const BASE_URL = 'https://world.openfoodfacts.org/api/v2/product';
const REQUEST_TIMEOUT_MS = 5000; const REQUEST_TIMEOUT_MS = 5000;
const isOffline = () => typeof navigator !== 'undefined' && 'onLine' in navigator && !navigator.onLine; const isOffline = () =>
typeof navigator !== 'undefined' && 'onLine' in navigator && navigator.onLine === false;
export const fetchProductFromOFF = async (barcode: string): Promise<ExternalProductInfo | null> => { export const fetchProductFromOFF = async (barcode: string): Promise<ExternalProductInfo | null> => {
if (!barcode || isOffline()) { if (!barcode || isOffline()) {