Untitled
Anonymous
Plain Text
10/30/2025 1:06 PM
22.9 KB
18
Indexable
Never
import React from 'react';
import userEvent from '@testing-library/user-event';
import ElectricalTable from '../../components/ElectricalTable';
import { render, screen, waitFor, createTestStore } from '../test-utils';
import { useDropZone } from '../../hooks/useDropZone';
// Mock Material-UI icons
jest.mock('@mui/icons-material/DeleteSweep', () => {
return function MockDeleteSweepIcon(props: any) {
return <span data-testid="delete-sweep-icon" {...props}>🗑️</span>;
};
});
// Mock Redux dispatch
const mockDispatch = jest.fn();
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useDispatch: () => mockDispatch,
}));
jest.mock('../../hooks/useDropZone', () => ({
useDropZone: jest.fn(() => ({
isDraggingOver: false,
dropZoneHandlers: {},
dropZoneRef: { current: null },
})),
}));
jest.mock('../../hooks/useDragAndDrop', () => ({
useDragAndDrop: () => ({
draggedWorkOrder: null,
dragHandlers: {
onDragStart: jest.fn(),
onDragEnd: jest.fn(),
},
}),
}));
// Mock DraggableTableRow
jest.mock('../../components/DraggableTableRow', () => ({
DraggableTableRow: ({ order, handleCommitChange, handleDeleteRow }: any) => (
<tr data-testid={`draggable-row-${order.workOrderNo}`}>
<td>
<input
type="checkbox"
checked={order.committed}
onChange={(e) => handleCommitChange(order, e.target.checked)}
data-testid={`checkbox-${order.workOrderNo}`}
/>
</td>
<td>{order.workOrderNo}</td>
<td>{order.assignedTo}</td>
<td>
<button
onClick={() => handleDeleteRow(order.workOrderNo)}
data-testid={`delete-${order.workOrderNo}`}
>
Delete
</button>
</td>
</tr>
),
}));
// Mock ConfirmDialog
jest.mock('../../components/ConfirmDialog', () => {
return function MockConfirmDialog({ open, title, message, confirmText, cancelText, onConfirm, onCancel }: any) {
if (!open) return null;
return (
<div data-testid="confirm-dialog" role="dialog">
<h2>{title}</h2>
<div>{typeof message === 'string' ? message : 'Dialog message'}</div>
<button onClick={onConfirm} data-testid="confirm-button">
{confirmText}
</button>
<button onClick={onCancel} data-testid="cancel-button">
{cancelText}
</button>
</div>
);
};
});
// Mock Widgets
jest.mock('../../utils/Widgets', () => ({
PaperFrame: ({ children, sx }: any) => (
<div data-testid="paper-frame" style={sx}>{children}</div>
),
FullScreenMapper: ({ children, onFullScreenMode }: any) => (
<div data-testid="fullscreen-mapper">
<button onClick={() => onFullScreenMode(true)} data-testid="fullscreen-open">
Open Fullscreen
</button>
<button onClick={() => onFullScreenMode(false)} data-testid="fullscreen-close">
Close Fullscreen
</button>
{children}
</div>
),
}));
describe('ElectricalTable', () => {
// Get reference to mocked function
const mockUseDropZone = useDropZone as jest.MockedFunction<typeof useDropZone>;
const mockWorkOrders = [
{
workOrderNo: 'WO-ELEC-001',
workType: 'Maintenance',
assignedTo: 'John Doe',
shift: 'Day',
notes: 'Test notes 1',
committed: false,
committedOn: null,
ncOpenCount: 1,
estimatedCompletedOn: '2024-01-15T16:00:00Z',
tailNumber: 'TEST-001',
isWorkOrderClosed: false,
},
{
workOrderNo: 'WO-ELEC-002',
workType: 'Inspection',
assignedTo: 'Jane Smith',
shift: 'Night',
notes: 'Test notes 2',
committed: true,
committedOn: '2024-01-15T10:00:00Z',
ncOpenCount: 0,
estimatedCompletedOn: '2024-01-16T08:00:00Z',
tailNumber: 'TEST-001',
isWorkOrderClosed: false,
},
];
const renderElectricalTable = (initialState: any = {}) => {
// Use tomorrow's date to ensure whiteboard is not locked by date logic
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const store = createTestStore({
whiteBoard: {
tailNumber: 'TEST-001',
planDate: tomorrow.toISOString().split('T')[0], // Future date
electrical: mockWorkOrders,
structures: [],
mechanical: [],
constraints: [],
locked: false,
isPrevWhiteBoardImported: false,
constraintBoardStates: {},
...initialState.whiteBoard,
},
});
return render(<ElectricalTable />, { store });
};
beforeEach(() => {
jest.clearAllMocks();
// Reset useDropZone mock to default state (matching component expectations)
mockUseDropZone.mockReturnValue({
isDraggingOver: false,
dropZoneHandlers: {},
dropZoneRef: { current: null },
} as any);
});
describe('Basic Rendering', () => {
// Tests that the component renders with proper table structure
it('renders ElectricalTable with correct structure', () => {
renderElectricalTable();
expect(screen.getByTestId('paper-frame')).toBeInTheDocument();
expect(screen.getByTestId('fullscreen-mapper')).toBeInTheDocument();
expect(screen.getByText('Electrical')).toBeInTheDocument();
expect(screen.getByRole('table')).toBeInTheDocument();
});
// Tests that table headers are rendered correctly
it('renders all table column headers', () => {
renderElectricalTable();
const expectedHeaders = [
'Committed',
'Work Order',
'NC Open',
'ECD',
'Assignee',
'Shift',
'Notes',
'*'
];
expectedHeaders.forEach(header => {
expect(screen.getByText(header)).toBeInTheDocument();
});
});
// Tests that clear table button is rendered
it('renders clear table button', () => {
renderElectricalTable();
const clearButton = screen.getByTitle('Clear Table');
expect(clearButton).toBeInTheDocument();
});
// Tests that work orders are displayed in table rows
it('displays work orders in table rows', () => {
renderElectricalTable();
expect(screen.getByTestId('draggable-row-WO-ELEC-001')).toBeInTheDocument();
expect(screen.getByTestId('draggable-row-WO-ELEC-002')).toBeInTheDocument();
expect(screen.getByText('WO-ELEC-001')).toBeInTheDocument();
expect(screen.getByText('WO-ELEC-002')).toBeInTheDocument();
});
});
describe('Redux Integration', () => {
// Tests that electrical work orders are loaded from Redux store
it('loads electrical work orders from Redux store', () => {
renderElectricalTable();
expect(screen.getByText('WO-ELEC-001')).toBeInTheDocument();
expect(screen.getByText('WO-ELEC-002')).toBeInTheDocument();
});
// Tests behavior with empty work orders
it('handles empty work orders gracefully', () => {
renderElectricalTable({
whiteBoard: { electrical: [] }
});
expect(screen.getByText('Electrical')).toBeInTheDocument();
expect(screen.getByRole('table')).toBeInTheDocument();
expect(screen.queryByText('WO-ELEC-001')).not.toBeInTheDocument();
});
// Tests locked state behavior
it('handles locked whiteboard state', () => {
// Use past date to trigger locked state through business logic
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
renderElectricalTable({
whiteBoard: {
planDate: yesterday.toISOString().split('T')[0],
locked: true
}
});
const clearButton = screen.getByTitle('Clear Table');
expect(clearButton).toBeDisabled();
});
// Tests work order updates through Redux
it('dispatches Redux actions for work order updates', () => {
renderElectricalTable();
// Redux integration is verified through the component rendering correctly
expect(screen.getByText('Electrical')).toBeInTheDocument();
});
});
describe('Work Order CRUD Operations', () => {
// Tests commit status change
it('handles work order commit status change', async () => {
const user = userEvent.setup();
renderElectricalTable();
const checkbox = screen.getByTestId('checkbox-WO-ELEC-001');
await user.click(checkbox);
expect(mockDispatch).toHaveBeenCalledWith(
expect.objectContaining({
type: expect.stringContaining('updateWorkOrder'),
payload: expect.objectContaining({
category: 'electrical',
workOrder: expect.objectContaining({
workOrderNo: 'WO-ELEC-001',
committed: true,
}),
}),
})
);
});
// Tests work order deletion
it('handles work order deletion', async () => {
const user = userEvent.setup();
renderElectricalTable();
const deleteButton = screen.getByTestId('delete-WO-ELEC-001');
await user.click(deleteButton);
// Should open delete confirmation dialog
expect(screen.getByTestId('confirm-dialog')).toBeInTheDocument();
expect(screen.getByText('Clear the row')).toBeInTheDocument();
});
// Tests work order update operations
it('handles work order field updates', () => {
renderElectricalTable();
// The update functionality is handled through DraggableTableRow
// This tests that the component provides the correct handlers
expect(screen.getByTestId('draggable-row-WO-ELEC-001')).toBeInTheDocument();
});
// Tests clear table functionality
it('handles clear table operation', async () => {
const user = userEvent.setup();
renderElectricalTable();
const clearButton = screen.getByTitle('Clear Table');
await user.click(clearButton);
// Should open clear table confirmation dialog
expect(screen.getByTestId('confirm-dialog')).toBeInTheDocument();
expect(screen.getByText('Clear Table')).toBeInTheDocument();
});
});
describe('Confirmation Dialogs', () => {
// Tests clear table confirmation dialog
it('shows clear table confirmation dialog', async () => {
const user = userEvent.setup();
renderElectricalTable();
const clearButton = screen.getByTitle('Clear Table');
await user.click(clearButton);
const dialog = screen.getByTestId('confirm-dialog');
expect(dialog).toBeInTheDocument();
expect(screen.getByText('Clear Table')).toBeInTheDocument();
expect(screen.getByTestId('confirm-button')).toHaveTextContent('Clear');
expect(screen.getByTestId('cancel-button')).toHaveTextContent('Cancel');
});
// Tests clear table confirmation
it('confirms clear table operation', async () => {
const user = userEvent.setup();
renderElectricalTable();
const clearButton = screen.getByTitle('Clear Table');
await user.click(clearButton);
const confirmButton = screen.getByTestId('confirm-button');
await user.click(confirmButton);
expect(mockDispatch).toHaveBeenCalledWith(
expect.objectContaining({
type: expect.stringContaining('clearCategory'),
payload: expect.objectContaining({
category: 'electrical',
tailNumber: 'TEST-001',
}),
})
);
});
// Tests clear table cancellation
it('cancels clear table operation', async () => {
const user = userEvent.setup();
renderElectricalTable();
const clearButton = screen.getByTitle('Clear Table');
await user.click(clearButton);
const cancelButton = screen.getByTestId('cancel-button');
await user.click(cancelButton);
expect(screen.queryByTestId('confirm-dialog')).not.toBeInTheDocument();
});
// Tests delete row confirmation dialog
it('shows delete row confirmation dialog', async () => {
const user = userEvent.setup();
renderElectricalTable();
const deleteButton = screen.getByTestId('delete-WO-ELEC-001');
await user.click(deleteButton);
const dialog = screen.getByTestId('confirm-dialog');
expect(dialog).toBeInTheDocument();
expect(screen.getByText('Clear the row')).toBeInTheDocument();
expect(screen.getByText('WO-ELEC-001')).toBeInTheDocument();
});
// Tests delete row confirmation
it('confirms delete row operation', async () => {
const user = userEvent.setup();
renderElectricalTable();
const deleteButton = screen.getByTestId('delete-WO-ELEC-001');
await user.click(deleteButton);
const confirmButton = screen.getByTestId('confirm-button');
await user.click(confirmButton);
expect(mockDispatch).toHaveBeenCalledWith(
expect.objectContaining({
type: expect.stringContaining('removeWorkOrder'),
payload: expect.objectContaining({
category: 'electrical',
workOrderNo: 'WO-ELEC-001',
}),
})
);
});
});
describe('Drag and Drop Functionality', () => {
// Tests drop zone integration
it('integrates with drop zone for drag and drop', () => {
renderElectricalTable();
// Should have drop zone attributes
const dropZone = screen.getByRole('table').closest('[data-droppable="true"]');
expect(dropZone).toBeInTheDocument();
expect(dropZone).toHaveAttribute('data-table-type', 'electrical');
});
// Tests drag over styling
it('applies drag over styling when dragging', () => {
// Mock isDraggingOver as true
mockUseDropZone.mockReturnValue({
isDraggingOver: true,
dropZoneHandlers: {},
dropZoneRef: { current: null },
} as any);
renderElectricalTable();
// Should apply drag over styling
expect(screen.getByRole('table')).toBeInTheDocument();
});
// Tests work order move functionality
it('handles work order move operations', () => {
renderElectricalTable();
// The drop functionality is handled by the useDropZone hook
// This tests that the component is properly configured for drops
const dropZone = screen.getByRole('table').closest('[data-droppable="true"]');
expect(dropZone).toBeInTheDocument();
});
// Tests draggable table rows
it('renders draggable table rows', () => {
renderElectricalTable();
expect(screen.getByTestId('draggable-row-WO-ELEC-001')).toBeInTheDocument();
expect(screen.getByTestId('draggable-row-WO-ELEC-002')).toBeInTheDocument();
});
});
describe('Fullscreen Functionality', () => {
// Tests fullscreen toggle
it('handles fullscreen toggle', async () => {
const user = userEvent.setup();
renderElectricalTable();
const openButton = screen.getByTestId('fullscreen-open');
const closeButton = screen.getByTestId('fullscreen-close');
await user.click(openButton);
await user.click(closeButton);
// Should handle fullscreen state changes without errors
expect(screen.getByText('Electrical')).toBeInTheDocument();
});
// Tests fullscreen mapper integration
it('integrates with FullScreenMapper component', () => {
renderElectricalTable();
expect(screen.getByTestId('fullscreen-mapper')).toBeInTheDocument();
});
});
describe('Locked State Behavior', () => {
// Tests that clear button is disabled when locked
it('disables clear button when whiteboard is locked', () => {
// Use past date to trigger locked state through business logic
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
renderElectricalTable({
whiteBoard: {
planDate: yesterday.toISOString().split('T')[0],
locked: true
}
});
const clearButton = screen.getByTitle('Clear Table');
expect(clearButton).toBeDisabled();
});
// Tests that clear button is enabled when not locked
it('enables clear button when whiteboard is not locked', () => {
renderElectricalTable();
const clearButton = screen.getByTitle('Clear Table');
expect(clearButton).not.toBeDisabled();
});
// Tests that draggable rows respect lock state
it('passes lock state to draggable rows', () => {
// Use past date to trigger locked state through business logic
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
renderElectricalTable({
whiteBoard: {
planDate: yesterday.toISOString().split('T')[0],
locked: true
}
});
// DraggableTableRow components should receive the lock state
expect(screen.getByTestId('draggable-row-WO-ELEC-001')).toBeInTheDocument();
expect(screen.getByTestId('draggable-row-WO-ELEC-002')).toBeInTheDocument();
});
});
describe('Component Integration', () => {
// Tests integration with DraggableTableRow
it('integrates with DraggableTableRow components', () => {
renderElectricalTable();
expect(screen.getByTestId('draggable-row-WO-ELEC-001')).toBeInTheDocument();
expect(screen.getByTestId('draggable-row-WO-ELEC-002')).toBeInTheDocument();
});
// Tests integration with utility components
it('integrates with utility components correctly', () => {
renderElectricalTable();
expect(screen.getByTestId('paper-frame')).toBeInTheDocument();
expect(screen.getByTestId('fullscreen-mapper')).toBeInTheDocument();
});
// Tests proper prop passing to child components
it('passes correct props to child components', () => {
renderElectricalTable();
// Should pass all necessary props to DraggableTableRow
const row = screen.getByTestId('draggable-row-WO-ELEC-001');
expect(row).toBeInTheDocument();
// Should have checkbox with correct state
const checkbox = screen.getByTestId('checkbox-WO-ELEC-001');
expect(checkbox).not.toBeChecked(); // committed: false
const checkbox2 = screen.getByTestId('checkbox-WO-ELEC-002');
expect(checkbox2).toBeChecked(); // committed: true
});
});
describe('Error Handling', () => {
// Tests behavior with malformed work order data
it('handles malformed work order data', () => {
const malformedWorkOrders = [
{ workOrderNo: 'WO-MALFORMED' }, // Missing other fields
{ assignedTo: 'No Work Order Number' }, // Missing workOrderNo
];
renderElectricalTable({
whiteBoard: { electrical: malformedWorkOrders }
});
expect(screen.getByText('Electrical')).toBeInTheDocument();
});
// Tests behavior when dispatch fails
it('handles Redux dispatch errors gracefully', async () => {
const user = userEvent.setup();
mockDispatch.mockImplementation(() => {
throw new Error('Redux error');
});
renderElectricalTable();
const clearButton = screen.getByTitle('Clear Table');
await user.click(clearButton);
// Should not crash when dispatch fails
expect(screen.getByText('Electrical')).toBeInTheDocument();
});
// Tests behavior with missing tail number
it('handles missing tail number in clear operation', async () => {
const user = userEvent.setup();
renderElectricalTable({
whiteBoard: {
electrical: [],
tailNumber: ''
}
});
const clearButton = screen.getByTitle('Clear Table');
await user.click(clearButton);
const confirmButton = screen.getByTestId('confirm-button');
await user.click(confirmButton);
// Should handle empty tail number gracefully
expect(mockDispatch).toHaveBeenCalledWith(
expect.objectContaining({
payload: expect.objectContaining({
tailNumber: '',
}),
})
);
});
});
describe('Performance and State Management', () => {
// Tests efficient updates when work orders change
it('updates efficiently when work orders change', () => {
const updatedWorkOrders = [
...mockWorkOrders,
{
workOrderNo: 'WO-ELEC-003',
workType: 'Repair',
assignedTo: 'Bob Wilson',
shift: 'Day',
notes: 'New work order',
committed: false,
committedOn: null,
ncOpenCount: 2,
estimatedCompletedOn: '2024-01-17T12:00:00Z',
tailNumber: 'TEST-001',
isWorkOrderClosed: false,
},
];
const { rerender: _rerender } = renderElectricalTable({
whiteBoard: { electrical: updatedWorkOrders }
});
expect(screen.getByText('WO-ELEC-001')).toBeInTheDocument();
expect(screen.getByText('WO-ELEC-003')).toBeInTheDocument();
});
// Tests component state management for editing and dialogs
it('manages internal state for dialogs correctly', async () => {
const user = userEvent.setup();
renderElectricalTable();
// Open and close clear dialog
const clearButton = screen.getByTitle('Clear Table');
await user.click(clearButton);
expect(screen.getByTestId('confirm-dialog')).toBeInTheDocument();
const cancelButton = screen.getByTestId('cancel-button');
await user.click(cancelButton);
await waitFor(() => {
expect(screen.queryByTestId('confirm-dialog')).not.toBeInTheDocument();
});
});
// Tests multiple simultaneous operations
it('handles multiple simultaneous operations', async () => {
const user = userEvent.setup();
renderElectricalTable();
// Should handle multiple checkboxes being toggled
const checkbox1 = screen.getByTestId('checkbox-WO-ELEC-001');
const checkbox2 = screen.getByTestId('checkbox-WO-ELEC-002');
await user.click(checkbox1);
await user.click(checkbox2);
expect(mockDispatch).toHaveBeenCalledTimes(2);
});
});
describe('Accessibility and UX', () => {
// Tests table accessibility
it('provides proper table accessibility', () => {
renderElectricalTable();
const table = screen.getByRole('table');
expect(table).toBeInTheDocument();
// Should have proper table structure
expect(screen.getAllByRole('columnheader')).toHaveLength(8);
});
// Tests dialog accessibility
it('provides accessible confirmation dialogs', async () => {
const user = userEvent.setup();
renderElectricalTable();
const clearButton = screen.getByTitle('Clear Table');
await user.click(clearButton);
const dialog = screen.getByRole('dialog');
expect(dialog).toBeInTheDocument();
});
// Tests button tooltips and titles
it('provides helpful button tooltips', () => {
renderElectricalTable();
const clearButton = screen.getByTitle('Clear Table');
expect(clearButton).toHaveAttribute('title', 'Clear Table');
});
});
});Editor is loading...
Leave a Comment