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
}, [open, categoryOptions, initialBarcode]);
useEffect(() => {
if (!open || !barcode) return;
void lookupBarcode(barcode);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, barcode]);
useEffect(() => {
if (!barcode) {
setLookupStatus('idle');
@@ -181,7 +187,7 @@ export const AddProductDialog = ({
async function lookupBarcode(code: string) {
if (!code) return;
if (typeof navigator !== 'undefined' && 'onLine' in navigator && !navigator.onLine) {
if (typeof navigator !== 'undefined' && 'onLine' in navigator && navigator.onLine === false) {
setLookupStatus('offline');
setExternalProduct(null);
return;
+48 -36
View File
@@ -46,6 +46,7 @@ export const EditableEntityList = ({
onUpdate,
onDelete,
}: EditableEntityListProps) => {
const [nameOverrides, setNameOverrides] = useState<Record<string, string>>({});
const [newName, setNewName] = useState('');
const [editingId, setEditingId] = useState<string | null>(null);
const [editName, setEditName] = useState('');
@@ -92,6 +93,7 @@ export const EditableEntityList = ({
try {
const success = applyOutcome(setFeedback, await onUpdate(editingId, trimmed), `${entityLabel} updated.`);
if (success) {
setNameOverrides((prev) => ({ ...prev, [editingId]: trimmed }));
cancelEditing();
}
} catch (error) {
@@ -105,6 +107,13 @@ export const EditableEntityList = ({
if (success && editingId === id) {
cancelEditing();
}
if (success) {
setNameOverrides((prev) => {
const next = { ...prev };
delete next[id];
return next;
});
}
} catch (error) {
setFeedback({ text: `Unable to delete ${entityLabel.toLowerCase()}.`, severity: 'error' });
}
@@ -129,46 +138,49 @@ export const EditableEntityList = ({
</Button>
</Stack>
<List>
{entities.map((entity) => (
<ListItem key={entity.id} divider>
{editingId === entity.id ? (
<Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
<TextField
size="small"
fullWidth
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}`}
{entities.map((entity) => {
const displayName = nameOverrides[entity.id] ?? entity.name;
return (
<ListItem key={entity.id} divider>
{editingId === entity.id ? (
<Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
<TextField
size="small"
>
<EditIcon fontSize="small" />
fullWidth
value={editName}
onChange={(event) => setEditName(event.target.value)}
/>
<IconButton color="primary" onClick={handleSave} disabled={!canSave} aria-label={`Save ${entityLabel}`}>
<CheckIcon />
</IconButton>
<IconButton
onClick={() => handleDelete(entity.id, entity.name)}
aria-label={`Delete ${entity.name}`}
size="small"
>
<DeleteIcon fontSize="small" />
<IconButton onClick={cancelEditing} aria-label="Cancel editing">
<CloseIcon />
</IconButton>
</Stack>
</Stack>
)}
</ListItem>
))}
) : (
<Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
<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>
</Stack>
);
+27 -9
View File
@@ -8,6 +8,7 @@ import {
} from '@mui/material';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import SearchIcon from '@mui/icons-material/Search';
import ClearIcon from '@mui/icons-material/Clear';
import { useMemo, useState, useEffect } from 'react';
import { useCategories } from '../hooks/dataHooks';
import { Product } from '../models/Product';
@@ -97,16 +98,33 @@ export const ProductAutocomplete = ({
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">
<IconButton
aria-label="Add product"
size="small"
onClick={onAddProduct}
disabled={!onAddProduct}
>
<AddCircleOutlineIcon />
</IconButton>
<span>
<IconButton
aria-label="Add product"
size="small"
onClick={onAddProduct}
disabled={!onAddProduct}
>
<AddCircleOutlineIcon />
</IconButton>
</span>
</Tooltip>
</InputAdornment>
</>
@@ -52,7 +52,7 @@ describe('ProductRow edit/save and scanner behaviour', () => {
const clearButton = screen.getByText('Clear');
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);
const mockScan = await screen.findByText(/Mock Scan/i);
@@ -131,7 +131,7 @@ describe('ProductRow edit/save and scanner behaviour', () => {
if (!barcodeField) {
// 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);
const mockScanButton = await screen.findByText(/Mock Scan/i);
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.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 = () => {
setIsEditing(false);
setFormState(getInitialFormState(product, categoriesById));
setFieldErrors({});
};
@@ -102,33 +101,34 @@ export const ProductRow = ({ product, categories, categoriesById, onSave, onDele
</option>
))}
</TextField>
{formState.barcode ? (
<TextField
label="Barcode"
value={formState.barcode}
onChange={handleChange('barcode')}
size="small"
error={Boolean(fieldErrors.barcode)}
helperText={fieldErrors.barcode || undefined}
InputProps={{
endAdornment: (
<TextField
label="Barcode"
value={formState.barcode}
onChange={handleChange('barcode')}
size="small"
error={Boolean(fieldErrors.barcode)}
helperText={fieldErrors.barcode || undefined}
InputProps={{
endAdornment: (
<Stack direction="row" spacing={0.5} alignItems="center">
<Button size="small" onClick={() => setIsScannerOpen(true)} aria-label="Scan">
Scan barcode
</Button>
<Button
size="small"
onClick={() => {
setFormState((prev) => ({ ...prev, barcode: '' }));
setFieldErrors((prev) => ({ ...prev, barcode: undefined }));
}}
aria-label="Clear"
disabled={!formState.barcode}
>
Clear
</Button>
),
}}
/>
) : (
<Button variant="outlined" onClick={() => setIsScannerOpen(true)}>
Scan Barcode
</Button>
)}
</Stack>
),
}}
/>
<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">
<DeleteIcon fontSize="small" />
@@ -3,11 +3,13 @@ import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { AddProductDialog } from '../AddProductDialog';
import { createMockDb } from '../../testUtils/mockDb';
import * as offModule from '../../modules/openFoodFacts';
import type { Product } from '../../models/Product';
let mockDb = createMockDb();
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', () => ({
useDatabase: () => mockDb,
@@ -25,21 +27,21 @@ vi.mock('../BarcodeScannerView', () => ({
),
}));
vi.mock('../modules/openFoodFacts', () => ({
fetchProductFromOFF: (...args: unknown[]) => mockFetchProductFromOFF(...args),
}));
const defaultCategories = ['Fresh', 'Pantry'];
describe('AddProductDialog', () => {
beforeEach(() => {
mockDb = createMockDb();
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 () => {
vi.spyOn(window.navigator, 'onLine', 'get').mockReturnValue(false);
onlineSpy?.mockReturnValue(false);
render(
<AddProductDialog
@@ -55,7 +57,7 @@ describe('AddProductDialog', () => {
});
it('applies initialBarcode and triggers lookup', async () => {
mockFetchProductFromOFF.mockResolvedValue({ name: 'From OFF' });
fetchProductSpy.mockResolvedValue({ name: 'From OFF' });
render(
<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');
await waitFor(() => expect(screen.getByLabelText(/name/i)).toHaveValue('From OFF'));
});
@@ -58,8 +58,9 @@ describe('EditableEntityList', () => {
await waitFor(() => expect(screen.getByText('x')).toBeInTheDocument());
await user.click(screen.getByLabelText(/edit first/i));
await user.clear(screen.getByDisplayValue('First'));
await user.type(screen.getByDisplayValue('First'), 'Updated');
const firstInput = await screen.findByDisplayValue('First');
await user.clear(firstInput);
await user.type(firstInput, 'Updated');
await user.click(screen.getByLabelText(/save item/i));
await waitFor(() =>
@@ -94,8 +94,8 @@ describe('ProductRow error handling', () => {
// When barcode is empty, scanner button is shown and opens dialog
await user.click(screen.getByLabelText(/cancel edit/i));
await user.click(screen.getByLabelText(/edit product one/i));
await waitFor(() => expect(screen.getByRole('button', { name: /scan barcode/i })).toBeInTheDocument());
await user.click(screen.getByRole('button', { name: /scan barcode/i }));
await waitFor(() => expect(screen.getByRole('button', { name: /scan/i })).toBeInTheDocument());
await user.click(screen.getByRole('button', { name: /scan/i }));
expect(screen.getByRole('dialog', { name: /scan barcode/i })).toBeInTheDocument();
await user.click(screen.getByText(/mock scan/i));
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 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> => {
if (!barcode || isOffline()) {