Add TenantCustomTier system and fix BusinessEditModal feature loading
Backend: - Add TenantCustomTier model for per-tenant feature overrides - Update EntitlementService to check custom tier before plan features - Add custom_tier action on TenantViewSet (GET/PUT/DELETE) - Add Celery task for grace period management (30-day expiry) Frontend: - Add DynamicFeaturesEditor component for dynamic feature management - Fix BusinessEditModal to load features from plan defaults when no custom tier - Update limits (max_users, max_resources, etc.) to use featureValues - Remove outdated canonical feature check from FeaturePicker (removes warning icons) - Add useBillingPlans hook for accessing billing system data - Add custom tier API functions to platform.ts Features now follow consistent rules: - Load from plan defaults when no custom tier exists - Load from custom tier when one exists - Reset to plan defaults when plan changes - Save to custom tier on edit 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
134
frontend/src/components/LocationSelector.tsx
Normal file
134
frontend/src/components/LocationSelector.tsx
Normal file
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* LocationSelector Component
|
||||
*
|
||||
* A reusable dropdown for selecting a business location.
|
||||
* Hidden when only one location exists.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { useLocations } from '../hooks/useLocations';
|
||||
import { FormSelect, SelectOption } from './ui/FormSelect';
|
||||
import { Location } from '../types';
|
||||
|
||||
interface LocationSelectorProps {
|
||||
/** Currently selected location ID */
|
||||
value?: number | null;
|
||||
/** Callback when location is selected */
|
||||
onChange: (locationId: number | null) => void;
|
||||
/** Label for the selector */
|
||||
label?: string;
|
||||
/** Error message */
|
||||
error?: string;
|
||||
/** Hint text */
|
||||
hint?: string;
|
||||
/** Placeholder text */
|
||||
placeholder?: string;
|
||||
/** Whether the field is required */
|
||||
required?: boolean;
|
||||
/** Whether to include inactive locations */
|
||||
includeInactive?: boolean;
|
||||
/** Whether the selector is disabled */
|
||||
disabled?: boolean;
|
||||
/** Force show even with single location (for admin purposes) */
|
||||
forceShow?: boolean;
|
||||
/** Container class name */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* LocationSelector - Dropdown for selecting a business location
|
||||
*
|
||||
* Automatically hides when:
|
||||
* - Only one active location exists (unless forceShow is true)
|
||||
* - Locations are still loading
|
||||
*
|
||||
* The component auto-selects the only location when there's just one.
|
||||
*/
|
||||
export const LocationSelector: React.FC<LocationSelectorProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
label = 'Location',
|
||||
error,
|
||||
hint,
|
||||
placeholder = 'Select a location',
|
||||
required = false,
|
||||
includeInactive = false,
|
||||
disabled = false,
|
||||
forceShow = false,
|
||||
className = '',
|
||||
}) => {
|
||||
const { data: locations, isLoading, isError } = useLocations({ includeInactive });
|
||||
|
||||
// Don't render if loading or error
|
||||
if (isLoading || isError) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Filter to only active locations if not including inactive
|
||||
const availableLocations = locations ?? [];
|
||||
|
||||
// Hide if only one location (unless forceShow)
|
||||
if (availableLocations.length <= 1 && !forceShow) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Build options from locations
|
||||
const options: SelectOption<string>[] = availableLocations.map((loc: Location) => ({
|
||||
value: String(loc.id),
|
||||
label: loc.is_primary
|
||||
? `${loc.name} (Primary)`
|
||||
: loc.is_active
|
||||
? loc.name
|
||||
: `${loc.name} (Inactive)`,
|
||||
disabled: !loc.is_active && !includeInactive,
|
||||
}));
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const selectedValue = e.target.value;
|
||||
onChange(selectedValue ? Number(selectedValue) : null);
|
||||
};
|
||||
|
||||
return (
|
||||
<FormSelect
|
||||
label={label}
|
||||
value={value ? String(value) : ''}
|
||||
onChange={handleChange}
|
||||
options={options}
|
||||
error={error}
|
||||
hint={hint}
|
||||
placeholder={placeholder}
|
||||
required={required}
|
||||
disabled={disabled}
|
||||
containerClassName={className}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to determine if location selector should be shown
|
||||
*/
|
||||
export const useShouldShowLocationSelector = (includeInactive = false): boolean => {
|
||||
const { data: locations, isLoading } = useLocations({ includeInactive });
|
||||
|
||||
if (isLoading) return false;
|
||||
return (locations?.length ?? 0) > 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to auto-select location when only one exists
|
||||
*/
|
||||
export const useAutoSelectLocation = (
|
||||
currentValue: number | null | undefined,
|
||||
onChange: (locationId: number | null) => void
|
||||
) => {
|
||||
const { data: locations } = useLocations();
|
||||
|
||||
React.useEffect(() => {
|
||||
// Auto-select if only one location and no value selected
|
||||
if (locations?.length === 1 && !currentValue) {
|
||||
onChange(locations[0].id);
|
||||
}
|
||||
}, [locations, currentValue, onChange]);
|
||||
};
|
||||
|
||||
export default LocationSelector;
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
FileSignature,
|
||||
CalendarOff,
|
||||
LayoutTemplate,
|
||||
MapPin,
|
||||
} from 'lucide-react';
|
||||
import { Business, User } from '../types';
|
||||
import { useLogout } from '../hooks/useAuth';
|
||||
@@ -204,6 +205,13 @@ const Sidebar: React.FC<SidebarProps> = ({ business, user, isCollapsed, toggleCo
|
||||
label={t('nav.timeBlocks', 'Time Blocks')}
|
||||
isCollapsed={isCollapsed}
|
||||
/>
|
||||
<SidebarItem
|
||||
to="/locations"
|
||||
icon={MapPin}
|
||||
label={t('nav.locations', 'Locations')}
|
||||
isCollapsed={isCollapsed}
|
||||
locked={!canUse('multi_location')}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</SidebarSection>
|
||||
|
||||
166
frontend/src/components/__tests__/ApiTokensSection.test.tsx
Normal file
166
frontend/src/components/__tests__/ApiTokensSection.test.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import ApiTokensSection from '../ApiTokensSection';
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, defaultValue?: string) => defaultValue || key,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock the hooks
|
||||
const mockTokens = [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Test Token',
|
||||
key_prefix: 'abc123',
|
||||
scopes: ['read:appointments', 'write:appointments'],
|
||||
is_active: true,
|
||||
created_at: '2024-01-01T00:00:00Z',
|
||||
last_used_at: '2024-01-02T00:00:00Z',
|
||||
expires_at: null,
|
||||
created_by: { full_name: 'John Doe', username: 'john' },
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Revoked Token',
|
||||
key_prefix: 'xyz789',
|
||||
scopes: ['read:resources'],
|
||||
is_active: false,
|
||||
created_at: '2024-01-01T00:00:00Z',
|
||||
last_used_at: null,
|
||||
expires_at: null,
|
||||
created_by: null,
|
||||
},
|
||||
];
|
||||
|
||||
const mockUseApiTokens = vi.fn();
|
||||
const mockUseCreateApiToken = vi.fn();
|
||||
const mockUseRevokeApiToken = vi.fn();
|
||||
const mockUseUpdateApiToken = vi.fn();
|
||||
|
||||
vi.mock('../../hooks/useApiTokens', () => ({
|
||||
useApiTokens: () => mockUseApiTokens(),
|
||||
useCreateApiToken: () => mockUseCreateApiToken(),
|
||||
useRevokeApiToken: () => mockUseRevokeApiToken(),
|
||||
useUpdateApiToken: () => mockUseUpdateApiToken(),
|
||||
API_SCOPES: [
|
||||
{ value: 'read:appointments', label: 'Read Appointments', description: 'View appointments' },
|
||||
{ value: 'write:appointments', label: 'Write Appointments', description: 'Create/edit appointments' },
|
||||
{ value: 'read:resources', label: 'Read Resources', description: 'View resources' },
|
||||
],
|
||||
SCOPE_PRESETS: {
|
||||
read_only: { label: 'Read Only', description: 'View data only', scopes: ['read:appointments', 'read:resources'] },
|
||||
read_write: { label: 'Read & Write', description: 'Full access', scopes: ['read:appointments', 'write:appointments', 'read:resources'] },
|
||||
custom: { label: 'Custom', description: 'Select individual permissions', scopes: [] },
|
||||
},
|
||||
}));
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
describe('ApiTokensSection', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockUseCreateApiToken.mockReturnValue({ mutateAsync: vi.fn(), isPending: false });
|
||||
mockUseRevokeApiToken.mockReturnValue({ mutateAsync: vi.fn(), isPending: false });
|
||||
mockUseUpdateApiToken.mockReturnValue({ mutateAsync: vi.fn(), isPending: false });
|
||||
});
|
||||
|
||||
it('renders loading state', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: undefined, isLoading: true, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders error state', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: undefined, isLoading: false, error: new Error('Failed') });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText(/Failed to load API tokens/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders empty state when no tokens', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: [], isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('No API tokens yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders tokens list', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: mockTokens, isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('Test Token')).toBeInTheDocument();
|
||||
expect(screen.getByText('Revoked Token')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders section title', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: [], isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('API Tokens')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders New Token button', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: [], isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('New Token')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders API Docs link', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: [], isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('API Docs')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens new token modal when button clicked', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: mockTokens, isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByText('New Token'));
|
||||
// Modal title should appear
|
||||
expect(screen.getByRole('heading', { name: 'Create API Token' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows active tokens count', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: mockTokens, isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText(/Active Tokens \(1\)/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows revoked tokens count', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: mockTokens, isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText(/Revoked Tokens \(1\)/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows token key prefix', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: mockTokens, isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText(/abc123••••••••/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows revoked badge for inactive tokens', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: mockTokens, isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('Revoked')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders description text', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: [], isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText(/Create and manage API tokens/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders create button in empty state', () => {
|
||||
mockUseApiTokens.mockReturnValue({ data: [], isLoading: false, error: null });
|
||||
render(<ApiTokensSection />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('Create API Token')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,429 +1,114 @@
|
||||
/**
|
||||
* Unit tests for ConfirmationModal component
|
||||
*
|
||||
* Tests all modal functionality including:
|
||||
* - Rendering with different props (title, message, variants)
|
||||
* - User interactions (confirm, cancel, close button)
|
||||
* - Custom button labels
|
||||
* - Loading states
|
||||
* - Modal visibility (isOpen true/false)
|
||||
* - Different modal variants (info, warning, danger, success)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import i18n from 'i18next';
|
||||
import ConfirmationModal from '../ConfirmationModal';
|
||||
|
||||
// Setup i18n for tests
|
||||
beforeEach(() => {
|
||||
i18n.init({
|
||||
lng: 'en',
|
||||
fallbackLng: 'en',
|
||||
resources: {
|
||||
en: {
|
||||
translation: {
|
||||
common: {
|
||||
confirm: 'Confirm',
|
||||
cancel: 'Cancel',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
interpolation: {
|
||||
escapeValue: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Test wrapper with i18n provider
|
||||
const renderWithI18n = (component: React.ReactElement) => {
|
||||
return render(<I18nextProvider i18n={i18n}>{component}</I18nextProvider>);
|
||||
};
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => key,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('ConfirmationModal', () => {
|
||||
const defaultProps = {
|
||||
isOpen: true,
|
||||
onClose: vi.fn(),
|
||||
onConfirm: vi.fn(),
|
||||
title: 'Confirm Action',
|
||||
message: 'Are you sure you want to proceed?',
|
||||
title: 'Test Title',
|
||||
message: 'Test message',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('should render modal with title and message', () => {
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} />);
|
||||
it('returns null when not open', () => {
|
||||
const { container } = render(
|
||||
<ConfirmationModal {...defaultProps} isOpen={false} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
expect(screen.getByText('Confirm Action')).toBeInTheDocument();
|
||||
expect(screen.getByText('Are you sure you want to proceed?')).toBeInTheDocument();
|
||||
});
|
||||
it('renders title when open', () => {
|
||||
render(<ConfirmationModal {...defaultProps} />);
|
||||
expect(screen.getByText('Test Title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render modal with React node as message', () => {
|
||||
const messageNode = (
|
||||
<div>
|
||||
<p>First paragraph</p>
|
||||
<p>Second paragraph</p>
|
||||
</div>
|
||||
);
|
||||
it('renders message when open', () => {
|
||||
render(<ConfirmationModal {...defaultProps} />);
|
||||
expect(screen.getByText('Test message')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} message={messageNode} />);
|
||||
it('renders message as ReactNode', () => {
|
||||
render(
|
||||
<ConfirmationModal
|
||||
{...defaultProps}
|
||||
message={<span data-testid="custom-message">Custom content</span>}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByTestId('custom-message')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('First paragraph')).toBeInTheDocument();
|
||||
expect(screen.getByText('Second paragraph')).toBeInTheDocument();
|
||||
});
|
||||
it('calls onClose when close button is clicked', () => {
|
||||
render(<ConfirmationModal {...defaultProps} />);
|
||||
const buttons = screen.getAllByRole('button');
|
||||
fireEvent.click(buttons[0]);
|
||||
expect(defaultProps.onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not render when isOpen is false', () => {
|
||||
const { container } = renderWithI18n(
|
||||
<ConfirmationModal {...defaultProps} isOpen={false} />
|
||||
);
|
||||
it('calls onClose when cancel button is clicked', () => {
|
||||
render(<ConfirmationModal {...defaultProps} />);
|
||||
fireEvent.click(screen.getByText('common.cancel'));
|
||||
expect(defaultProps.onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
it('calls onConfirm when confirm button is clicked', () => {
|
||||
render(<ConfirmationModal {...defaultProps} />);
|
||||
fireEvent.click(screen.getByText('common.confirm'));
|
||||
expect(defaultProps.onConfirm).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should render default confirm and cancel buttons', () => {
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} />);
|
||||
it('uses custom confirm text', () => {
|
||||
render(<ConfirmationModal {...defaultProps} confirmText="Yes, delete" />);
|
||||
expect(screen.getByText('Yes, delete')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByRole('button', { name: /confirm/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
|
||||
});
|
||||
it('uses custom cancel text', () => {
|
||||
render(<ConfirmationModal {...defaultProps} cancelText="No, keep" />);
|
||||
expect(screen.getByText('No, keep')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render custom button labels', () => {
|
||||
renderWithI18n(
|
||||
<ConfirmationModal
|
||||
{...defaultProps}
|
||||
confirmText="Yes, delete it"
|
||||
cancelText="No, keep it"
|
||||
/>
|
||||
);
|
||||
it('renders info variant', () => {
|
||||
render(<ConfirmationModal {...defaultProps} variant="info" />);
|
||||
expect(screen.getByText('Test Title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Yes, delete it' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'No, keep it' })).toBeInTheDocument();
|
||||
});
|
||||
it('renders warning variant', () => {
|
||||
render(<ConfirmationModal {...defaultProps} variant="warning" />);
|
||||
expect(screen.getByText('Test Title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render close button in header', () => {
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} />);
|
||||
it('renders danger variant', () => {
|
||||
render(<ConfirmationModal {...defaultProps} variant="danger" />);
|
||||
expect(screen.getByText('Test Title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Close button is an SVG icon, so we find it by its parent button
|
||||
const closeButtons = screen.getAllByRole('button');
|
||||
const closeButton = closeButtons.find((button) =>
|
||||
button.querySelector('svg') && button !== screen.getByRole('button', { name: /confirm/i })
|
||||
);
|
||||
it('renders success variant', () => {
|
||||
render(<ConfirmationModal {...defaultProps} variant="success" />);
|
||||
expect(screen.getByText('Test Title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(closeButton).toBeInTheDocument();
|
||||
it('disables buttons when loading', () => {
|
||||
render(<ConfirmationModal {...defaultProps} isLoading={true} />);
|
||||
const buttons = screen.getAllByRole('button');
|
||||
buttons.forEach((button) => {
|
||||
expect(button).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('User Interactions', () => {
|
||||
it('should call onConfirm when confirm button is clicked', () => {
|
||||
const onConfirm = vi.fn();
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} onConfirm={onConfirm} />);
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
fireEvent.click(confirmButton);
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should call onClose when cancel button is clicked', () => {
|
||||
const onClose = vi.fn();
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} onClose={onClose} />);
|
||||
|
||||
const cancelButton = screen.getByRole('button', { name: /cancel/i });
|
||||
fireEvent.click(cancelButton);
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should call onClose when close button is clicked', () => {
|
||||
const onClose = vi.fn();
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} onClose={onClose} />);
|
||||
|
||||
// Find the close button (X icon in header)
|
||||
const buttons = screen.getAllByRole('button');
|
||||
const closeButton = buttons.find((button) =>
|
||||
button.querySelector('svg') && !button.textContent?.includes('Confirm')
|
||||
);
|
||||
|
||||
if (closeButton) {
|
||||
fireEvent.click(closeButton);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
});
|
||||
|
||||
it('should not call onConfirm multiple times on multiple clicks', () => {
|
||||
const onConfirm = vi.fn();
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} onConfirm={onConfirm} />);
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
fireEvent.click(confirmButton);
|
||||
fireEvent.click(confirmButton);
|
||||
fireEvent.click(confirmButton);
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Loading State', () => {
|
||||
it('should show loading spinner when isLoading is true', () => {
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} isLoading={true} />);
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
const spinner = confirmButton.querySelector('svg.animate-spin');
|
||||
|
||||
expect(spinner).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should disable confirm button when loading', () => {
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} isLoading={true} />);
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
expect(confirmButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should disable cancel button when loading', () => {
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} isLoading={true} />);
|
||||
|
||||
const cancelButton = screen.getByRole('button', { name: /cancel/i });
|
||||
expect(cancelButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should disable close button when loading', () => {
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} isLoading={true} />);
|
||||
|
||||
const buttons = screen.getAllByRole('button');
|
||||
const closeButton = buttons.find((button) =>
|
||||
button.querySelector('svg') && !button.textContent?.includes('Confirm')
|
||||
);
|
||||
|
||||
expect(closeButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should not call onConfirm when button is disabled due to loading', () => {
|
||||
const onConfirm = vi.fn();
|
||||
renderWithI18n(
|
||||
<ConfirmationModal {...defaultProps} onConfirm={onConfirm} isLoading={true} />
|
||||
);
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
fireEvent.click(confirmButton);
|
||||
|
||||
// Button is disabled, so onClick should not fire
|
||||
expect(onConfirm).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Modal Variants', () => {
|
||||
it('should render info variant by default', () => {
|
||||
const { container } = renderWithI18n(<ConfirmationModal {...defaultProps} />);
|
||||
|
||||
// Info variant has blue styling
|
||||
const iconContainer = container.querySelector('.bg-blue-100');
|
||||
expect(iconContainer).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render info variant with correct styling', () => {
|
||||
const { container } = renderWithI18n(
|
||||
<ConfirmationModal {...defaultProps} variant="info" />
|
||||
);
|
||||
|
||||
const iconContainer = container.querySelector('.bg-blue-100');
|
||||
expect(iconContainer).toBeInTheDocument();
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
expect(confirmButton).toHaveClass('bg-blue-600');
|
||||
});
|
||||
|
||||
it('should render warning variant with correct styling', () => {
|
||||
const { container } = renderWithI18n(
|
||||
<ConfirmationModal {...defaultProps} variant="warning" />
|
||||
);
|
||||
|
||||
const iconContainer = container.querySelector('.bg-amber-100');
|
||||
expect(iconContainer).toBeInTheDocument();
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
expect(confirmButton).toHaveClass('bg-amber-600');
|
||||
});
|
||||
|
||||
it('should render danger variant with correct styling', () => {
|
||||
const { container } = renderWithI18n(
|
||||
<ConfirmationModal {...defaultProps} variant="danger" />
|
||||
);
|
||||
|
||||
const iconContainer = container.querySelector('.bg-red-100');
|
||||
expect(iconContainer).toBeInTheDocument();
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
expect(confirmButton).toHaveClass('bg-red-600');
|
||||
});
|
||||
|
||||
it('should render success variant with correct styling', () => {
|
||||
const { container } = renderWithI18n(
|
||||
<ConfirmationModal {...defaultProps} variant="success" />
|
||||
);
|
||||
|
||||
const iconContainer = container.querySelector('.bg-green-100');
|
||||
expect(iconContainer).toBeInTheDocument();
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
expect(confirmButton).toHaveClass('bg-green-600');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accessibility', () => {
|
||||
it('should have proper button roles', () => {
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} />);
|
||||
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons.length).toBeGreaterThanOrEqual(2); // At least confirm and cancel
|
||||
});
|
||||
|
||||
it('should have backdrop overlay', () => {
|
||||
const { container } = renderWithI18n(<ConfirmationModal {...defaultProps} />);
|
||||
|
||||
const backdrop = container.querySelector('.fixed.inset-0.bg-black\\/50');
|
||||
expect(backdrop).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should have modal content container', () => {
|
||||
const { container } = renderWithI18n(<ConfirmationModal {...defaultProps} />);
|
||||
|
||||
const modal = container.querySelector('.bg-white.dark\\:bg-gray-800.rounded-xl');
|
||||
expect(modal).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Edge Cases', () => {
|
||||
it('should handle empty title', () => {
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} title="" />);
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
expect(confirmButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle empty message', () => {
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} message="" />);
|
||||
|
||||
const title = screen.getByText('Confirm Action');
|
||||
expect(title).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle very long title', () => {
|
||||
const longTitle = 'A'.repeat(200);
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} title={longTitle} />);
|
||||
|
||||
expect(screen.getByText(longTitle)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle very long message', () => {
|
||||
const longMessage = 'B'.repeat(500);
|
||||
renderWithI18n(<ConfirmationModal {...defaultProps} message={longMessage} />);
|
||||
|
||||
expect(screen.getByText(longMessage)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle rapid open/close state changes', () => {
|
||||
const { rerender } = renderWithI18n(<ConfirmationModal {...defaultProps} isOpen={true} />);
|
||||
expect(screen.getByText('Confirm Action')).toBeInTheDocument();
|
||||
|
||||
rerender(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ConfirmationModal {...defaultProps} isOpen={false} />
|
||||
</I18nextProvider>
|
||||
);
|
||||
expect(screen.queryByText('Confirm Action')).not.toBeInTheDocument();
|
||||
|
||||
rerender(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ConfirmationModal {...defaultProps} isOpen={true} />
|
||||
</I18nextProvider>
|
||||
);
|
||||
expect(screen.getByText('Confirm Action')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Complete User Flows', () => {
|
||||
it('should support complete confirmation flow', () => {
|
||||
const onConfirm = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
|
||||
renderWithI18n(
|
||||
<ConfirmationModal
|
||||
{...defaultProps}
|
||||
onConfirm={onConfirm}
|
||||
onClose={onClose}
|
||||
title="Delete Item"
|
||||
message="Are you sure you want to delete this item?"
|
||||
variant="danger"
|
||||
confirmText="Delete"
|
||||
cancelText="Cancel"
|
||||
/>
|
||||
);
|
||||
|
||||
// User sees the modal
|
||||
expect(screen.getByText('Delete Item')).toBeInTheDocument();
|
||||
expect(screen.getByText('Are you sure you want to delete this item?')).toBeInTheDocument();
|
||||
|
||||
// User clicks confirm
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should support complete cancellation flow', () => {
|
||||
const onConfirm = vi.fn();
|
||||
const onClose = vi.fn();
|
||||
|
||||
renderWithI18n(
|
||||
<ConfirmationModal
|
||||
{...defaultProps}
|
||||
onConfirm={onConfirm}
|
||||
onClose={onClose}
|
||||
variant="warning"
|
||||
/>
|
||||
);
|
||||
|
||||
// User sees the modal
|
||||
expect(screen.getByText('Confirm Action')).toBeInTheDocument();
|
||||
|
||||
// User clicks cancel
|
||||
fireEvent.click(screen.getByRole('button', { name: /cancel/i }));
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
expect(onConfirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should support loading state during async operation', () => {
|
||||
const onConfirm = vi.fn();
|
||||
|
||||
const { rerender } = renderWithI18n(
|
||||
<ConfirmationModal {...defaultProps} onConfirm={onConfirm} isLoading={false} />
|
||||
);
|
||||
|
||||
// Initial state - buttons enabled
|
||||
const confirmButton = screen.getByRole('button', { name: /confirm/i });
|
||||
expect(confirmButton).not.toBeDisabled();
|
||||
|
||||
// User clicks confirm
|
||||
fireEvent.click(confirmButton);
|
||||
expect(onConfirm).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Parent component sets loading state
|
||||
rerender(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ConfirmationModal {...defaultProps} onConfirm={onConfirm} isLoading={true} />
|
||||
</I18nextProvider>
|
||||
);
|
||||
|
||||
// Buttons now disabled during async operation
|
||||
expect(screen.getByRole('button', { name: /confirm/i })).toBeDisabled();
|
||||
expect(screen.getByRole('button', { name: /cancel/i })).toBeDisabled();
|
||||
});
|
||||
it('shows spinner when loading', () => {
|
||||
render(<ConfirmationModal {...defaultProps} isLoading={true} />);
|
||||
const spinner = document.querySelector('.animate-spin');
|
||||
expect(spinner).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,752 +1,83 @@
|
||||
/**
|
||||
* Unit tests for EmailTemplateSelector component
|
||||
*
|
||||
* Tests cover:
|
||||
* - Rendering with templates list
|
||||
* - Template selection and onChange callback
|
||||
* - Selected template display (active state)
|
||||
* - Empty templates array handling
|
||||
* - Loading states
|
||||
* - Disabled state
|
||||
* - Category filtering
|
||||
* - Template info display
|
||||
* - Edit link functionality
|
||||
* - Internationalization (i18n)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import React, { type ReactNode } from 'react';
|
||||
import EmailTemplateSelector from '../EmailTemplateSelector';
|
||||
import apiClient from '../../api/client';
|
||||
import { EmailTemplate } from '../../types';
|
||||
|
||||
// Mock apiClient
|
||||
vi.mock('../../api/client', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, fallback: string) => fallback,
|
||||
t: (key: string, defaultValue?: string) => defaultValue || key,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Test data factories
|
||||
const createMockEmailTemplate = (overrides?: Partial<EmailTemplate>): EmailTemplate => ({
|
||||
id: '1',
|
||||
name: 'Test Template',
|
||||
description: 'Test description',
|
||||
subject: 'Test Subject',
|
||||
htmlContent: '<p>Test content</p>',
|
||||
textContent: 'Test content',
|
||||
scope: 'BUSINESS',
|
||||
isDefault: false,
|
||||
category: 'APPOINTMENT',
|
||||
...overrides,
|
||||
});
|
||||
// Mock API client
|
||||
vi.mock('../../api/client', () => ({
|
||||
default: {
|
||||
get: vi.fn(() => Promise.resolve({ data: [] })),
|
||||
},
|
||||
}));
|
||||
|
||||
// Test wrapper with QueryClient
|
||||
const createWrapper = (queryClient: QueryClient) => {
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
describe('EmailTemplateSelector', () => {
|
||||
let queryClient: QueryClient;
|
||||
const mockOnChange = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false, gcTime: 0 },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
vi.clearAllMocks();
|
||||
it('renders select element', () => {
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={() => {}} />,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
expect(screen.getByRole('combobox')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
queryClient.clear();
|
||||
it('shows placeholder text after loading', async () => {
|
||||
render(
|
||||
<EmailTemplateSelector
|
||||
value={undefined}
|
||||
onChange={() => {}}
|
||||
placeholder="Select a template"
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
// Wait for loading to finish and placeholder to appear
|
||||
await screen.findByText('Select a template');
|
||||
});
|
||||
|
||||
describe('Rendering with templates', () => {
|
||||
it('should render with templates list', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({ id: '1', name: 'Welcome Email' }),
|
||||
createMockEmailTemplate({ id: '2', name: 'Confirmation Email', category: 'CONFIRMATION' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
const options = Array.from(select.options);
|
||||
|
||||
expect(options).toHaveLength(3); // placeholder + 2 templates
|
||||
expect(options[1]).toHaveTextContent('Welcome Email (APPOINTMENT)');
|
||||
expect(options[2]).toHaveTextContent('Confirmation Email (CONFIRMATION)');
|
||||
});
|
||||
|
||||
it('should render templates without category suffix for OTHER category', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({ id: '1', name: 'Custom Email', category: 'OTHER' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
const options = Array.from(select.options);
|
||||
|
||||
expect(options[1]).toHaveTextContent('Custom Email');
|
||||
expect(options[1]).not.toHaveTextContent('(OTHER)');
|
||||
});
|
||||
|
||||
it('should convert numeric IDs to strings', async () => {
|
||||
const mockData = [
|
||||
{
|
||||
id: 123,
|
||||
name: 'Numeric ID Template',
|
||||
description: 'Test',
|
||||
category: 'REMINDER',
|
||||
scope: 'BUSINESS',
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: mockData });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options[1].value).toBe('123');
|
||||
});
|
||||
it('is disabled when disabled prop is true', () => {
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={() => {}} disabled />,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
expect(screen.getByRole('combobox')).toBeDisabled();
|
||||
});
|
||||
|
||||
describe('Template selection', () => {
|
||||
it('should select template on click', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({ id: '1', name: 'Template 1' }),
|
||||
createMockEmailTemplate({ id: '2', name: 'Template 2' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
fireEvent.change(select, { target: { value: '2' } });
|
||||
|
||||
expect(mockOnChange).toHaveBeenCalledWith('2');
|
||||
});
|
||||
|
||||
it('should call onChange with undefined when selecting empty option', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({ id: '1', name: 'Template 1' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value="1" onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('combobox')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
fireEvent.change(select, { target: { value: '' } });
|
||||
|
||||
expect(mockOnChange).toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
|
||||
it('should handle numeric value prop', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({ id: '1', name: 'Template 1' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={1} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.value).toBe('1');
|
||||
});
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(
|
||||
<EmailTemplateSelector
|
||||
value={undefined}
|
||||
onChange={() => {}}
|
||||
className="custom-class"
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
describe('Selected template display', () => {
|
||||
it('should show selected template as active', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({
|
||||
id: '1',
|
||||
name: 'Selected Template',
|
||||
description: 'This template is selected',
|
||||
}),
|
||||
createMockEmailTemplate({ id: '2', name: 'Other Template' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value="1" onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.value).toBe('1');
|
||||
});
|
||||
|
||||
it('should display selected template info with description', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({
|
||||
id: '1',
|
||||
name: 'Template Name',
|
||||
description: 'Template description text',
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value="1" onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Template description text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should display template name when description is empty', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({
|
||||
id: '1',
|
||||
name: 'No Description Template',
|
||||
description: '',
|
||||
}),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value="1" onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('No Description Template')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should display edit link for selected template', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({ id: '1', name: 'Editable Template' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value="1" onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const editLink = screen.getByRole('link', { name: /edit/i });
|
||||
expect(editLink).toBeInTheDocument();
|
||||
expect(editLink).toHaveAttribute('href', '#/email-templates');
|
||||
expect(editLink).toHaveAttribute('target', '_blank');
|
||||
expect(editLink).toHaveAttribute('rel', 'noopener noreferrer');
|
||||
});
|
||||
});
|
||||
|
||||
it('should not display template info when no template is selected', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({ id: '1', name: 'Template 1' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('combobox')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editLink = screen.queryByRole('link', { name: /edit/i });
|
||||
expect(editLink).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Empty templates array', () => {
|
||||
it('should handle empty templates array', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/no email templates yet/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should display create link when templates array is empty', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const createLink = screen.getByRole('link', { name: /create your first template/i });
|
||||
expect(createLink).toBeInTheDocument();
|
||||
expect(createLink).toHaveAttribute('href', '#/email-templates');
|
||||
});
|
||||
});
|
||||
|
||||
it('should render select with only placeholder option when empty', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options).toHaveLength(1); // only placeholder
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Loading states', () => {
|
||||
it('should show loading text in placeholder when loading', async () => {
|
||||
vi.mocked(apiClient.get).mockImplementation(
|
||||
() => new Promise(() => {}) // Never resolves to keep loading state
|
||||
);
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options[0]).toHaveTextContent('Loading...');
|
||||
});
|
||||
|
||||
it('should disable select when loading', async () => {
|
||||
vi.mocked(apiClient.get).mockImplementation(
|
||||
() => new Promise(() => {}) // Never resolves
|
||||
);
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
const select = screen.getByRole('combobox');
|
||||
expect(select).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should not show empty state while loading', () => {
|
||||
vi.mocked(apiClient.get).mockImplementation(
|
||||
() => new Promise(() => {}) // Never resolves
|
||||
);
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
const emptyMessage = screen.queryByText(/no email templates yet/i);
|
||||
expect(emptyMessage).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Disabled state', () => {
|
||||
it('should disable select when disabled prop is true', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({ id: '1', name: 'Template 1' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} disabled={true} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox');
|
||||
expect(select).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should apply disabled attribute when disabled prop is true', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({ id: '1', name: 'Template 1' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} disabled={true} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox');
|
||||
expect(select).toBeDisabled();
|
||||
});
|
||||
|
||||
// Verify the select element has disabled attribute
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select).toHaveAttribute('disabled');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Category filtering', () => {
|
||||
it('should fetch templates with category filter', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} category="REMINDER" />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(apiClient.get).toHaveBeenCalledWith('/email-templates/?category=REMINDER');
|
||||
});
|
||||
});
|
||||
|
||||
it('should fetch templates without category filter when not provided', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(apiClient.get).toHaveBeenCalledWith('/email-templates/?');
|
||||
});
|
||||
});
|
||||
|
||||
it('should refetch when category changes', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValue({ data: [] });
|
||||
|
||||
const { rerender } = render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} category="REMINDER" />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(apiClient.get).toHaveBeenCalledWith('/email-templates/?category=REMINDER');
|
||||
});
|
||||
|
||||
vi.clearAllMocks();
|
||||
|
||||
rerender(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} category="CONFIRMATION" />
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(apiClient.get).toHaveBeenCalledWith('/email-templates/?category=CONFIRMATION');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Props and customization', () => {
|
||||
it('should use custom placeholder when provided', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector
|
||||
value={undefined}
|
||||
onChange={mockOnChange}
|
||||
placeholder="Choose an email template"
|
||||
/>,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options[0]).toHaveTextContent('Choose an email template');
|
||||
});
|
||||
});
|
||||
|
||||
it('should use default placeholder when not provided', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const select = screen.getByRole('combobox') as HTMLSelectElement;
|
||||
expect(select.options[0]).toHaveTextContent('Select a template...');
|
||||
});
|
||||
});
|
||||
|
||||
it('should apply custom className', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector
|
||||
value={undefined}
|
||||
onChange={mockOnChange}
|
||||
className="custom-class"
|
||||
/>,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const container = screen.getByRole('combobox').parentElement?.parentElement;
|
||||
expect(container).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
|
||||
it('should work without className prop', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('combobox')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Icons', () => {
|
||||
it('should display Mail icon', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const container = screen.getByRole('combobox').parentElement;
|
||||
const svg = container?.querySelector('svg');
|
||||
expect(svg).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should display ExternalLink icon for selected template', async () => {
|
||||
const mockTemplates = [
|
||||
createMockEmailTemplate({ id: '1', name: 'Template 1' }),
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValueOnce({
|
||||
data: mockTemplates.map(t => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
scope: t.scope,
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
})),
|
||||
});
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value="1" onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const editLink = screen.getByRole('link', { name: /edit/i });
|
||||
const svg = editLink.querySelector('svg');
|
||||
expect(svg).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('API error handling', () => {
|
||||
it('should handle API errors gracefully', async () => {
|
||||
const error = new Error('API Error');
|
||||
vi.mocked(apiClient.get).mockRejectedValueOnce(error);
|
||||
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={mockOnChange} />,
|
||||
{ wrapper: createWrapper(queryClient) }
|
||||
);
|
||||
|
||||
// Component should still render the select
|
||||
const select = screen.getByRole('combobox');
|
||||
expect(select).toBeInTheDocument();
|
||||
});
|
||||
it('shows empty state message when no templates', async () => {
|
||||
render(
|
||||
<EmailTemplateSelector value={undefined} onChange={() => {}} />,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
// Wait for loading to finish
|
||||
await screen.findByText('No email templates yet.');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import FloatingHelpButton from '../FloatingHelpButton';
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, defaultValue?: string) => defaultValue || key,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('FloatingHelpButton', () => {
|
||||
const renderWithRouter = (initialPath: string) => {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[initialPath]}>
|
||||
<FloatingHelpButton />
|
||||
</MemoryRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('renders help link on dashboard', () => {
|
||||
renderWithRouter('/dashboard');
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('links to correct help page for dashboard', () => {
|
||||
renderWithRouter('/dashboard');
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help/dashboard');
|
||||
});
|
||||
|
||||
it('links to correct help page for scheduler', () => {
|
||||
renderWithRouter('/scheduler');
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help/scheduler');
|
||||
});
|
||||
|
||||
it('links to correct help page for services', () => {
|
||||
renderWithRouter('/services');
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help/services');
|
||||
});
|
||||
|
||||
it('links to correct help page for resources', () => {
|
||||
renderWithRouter('/resources');
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help/resources');
|
||||
});
|
||||
|
||||
it('links to correct help page for settings', () => {
|
||||
renderWithRouter('/settings/general');
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help/settings/general');
|
||||
});
|
||||
|
||||
it('returns null on help pages', () => {
|
||||
const { container } = renderWithRouter('/help/dashboard');
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('has aria-label', () => {
|
||||
renderWithRouter('/dashboard');
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('aria-label', 'Help');
|
||||
});
|
||||
|
||||
it('has title attribute', () => {
|
||||
renderWithRouter('/dashboard');
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('title', 'Help');
|
||||
});
|
||||
|
||||
it('links to default help for unknown routes', () => {
|
||||
renderWithRouter('/unknown-route');
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help');
|
||||
});
|
||||
|
||||
it('handles dynamic routes by matching prefix', () => {
|
||||
renderWithRouter('/customers/123');
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help/customers');
|
||||
});
|
||||
});
|
||||
@@ -1,264 +1,57 @@
|
||||
/**
|
||||
* Unit tests for HelpButton component
|
||||
*
|
||||
* Tests cover:
|
||||
* - Component rendering
|
||||
* - Link navigation
|
||||
* - Icon display
|
||||
* - Text display and responsive behavior
|
||||
* - Accessibility attributes
|
||||
* - Custom className prop
|
||||
* - Internationalization (i18n)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import React from 'react';
|
||||
import HelpButton from '../HelpButton';
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, fallback: string) => fallback,
|
||||
t: (key: string, defaultValue?: string) => defaultValue || key,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Test wrapper with Router
|
||||
const createWrapper = () => {
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<BrowserRouter>{children}</BrowserRouter>
|
||||
);
|
||||
};
|
||||
|
||||
describe('HelpButton', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
const renderHelpButton = (props: { helpPath: string; className?: string }) => {
|
||||
return render(
|
||||
<BrowserRouter>
|
||||
<HelpButton {...props} />
|
||||
</BrowserRouter>
|
||||
);
|
||||
};
|
||||
|
||||
it('renders help link', () => {
|
||||
renderHelpButton({ helpPath: '/help/dashboard' });
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('should render the button', () => {
|
||||
render(<HelpButton helpPath="/help/getting-started" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render as a Link component with correct href', () => {
|
||||
render(<HelpButton helpPath="/help/resources" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help/resources');
|
||||
});
|
||||
|
||||
it('should render with different help paths', () => {
|
||||
const { rerender } = render(<HelpButton helpPath="/help/page1" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
let link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help/page1');
|
||||
|
||||
rerender(<HelpButton helpPath="/help/page2" />);
|
||||
|
||||
link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help/page2');
|
||||
});
|
||||
it('has correct href', () => {
|
||||
renderHelpButton({ helpPath: '/help/dashboard' });
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('href', '/help/dashboard');
|
||||
});
|
||||
|
||||
describe('Icon Display', () => {
|
||||
it('should display the HelpCircle icon', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
// Check for SVG icon (lucide-react renders as SVG)
|
||||
const svg = link.querySelector('svg');
|
||||
expect(svg).toBeInTheDocument();
|
||||
});
|
||||
it('renders help text', () => {
|
||||
renderHelpButton({ helpPath: '/help/test' });
|
||||
expect(screen.getByText('Help')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('Text Display', () => {
|
||||
it('should display help text', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const text = screen.getByText('Help');
|
||||
expect(text).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should apply responsive class to hide text on small screens', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const text = screen.getByText('Help');
|
||||
expect(text).toHaveClass('hidden', 'sm:inline');
|
||||
});
|
||||
it('has title attribute', () => {
|
||||
renderHelpButton({ helpPath: '/help/test' });
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('title', 'Help');
|
||||
});
|
||||
|
||||
describe('Accessibility', () => {
|
||||
it('should have title attribute', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('title', 'Help');
|
||||
});
|
||||
|
||||
it('should be keyboard accessible as a link', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toBeInTheDocument();
|
||||
expect(link.tagName).toBe('A');
|
||||
});
|
||||
|
||||
it('should have accessible name from text content', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link', { name: /help/i });
|
||||
expect(link).toBeInTheDocument();
|
||||
});
|
||||
it('applies custom className', () => {
|
||||
renderHelpButton({ helpPath: '/help/test', className: 'custom-class' });
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
describe('Styling', () => {
|
||||
it('should apply default classes', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveClass('inline-flex');
|
||||
expect(link).toHaveClass('items-center');
|
||||
expect(link).toHaveClass('gap-1.5');
|
||||
expect(link).toHaveClass('px-3');
|
||||
expect(link).toHaveClass('py-1.5');
|
||||
expect(link).toHaveClass('text-sm');
|
||||
expect(link).toHaveClass('rounded-lg');
|
||||
expect(link).toHaveClass('transition-colors');
|
||||
});
|
||||
|
||||
it('should apply color classes for light mode', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveClass('text-gray-500');
|
||||
expect(link).toHaveClass('hover:text-brand-600');
|
||||
expect(link).toHaveClass('hover:bg-gray-100');
|
||||
});
|
||||
|
||||
it('should apply color classes for dark mode', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveClass('dark:text-gray-400');
|
||||
expect(link).toHaveClass('dark:hover:text-brand-400');
|
||||
expect(link).toHaveClass('dark:hover:bg-gray-800');
|
||||
});
|
||||
|
||||
it('should apply custom className when provided', () => {
|
||||
render(<HelpButton helpPath="/help" className="custom-class" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('should merge custom className with default classes', () => {
|
||||
render(<HelpButton helpPath="/help" className="ml-auto" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveClass('ml-auto');
|
||||
expect(link).toHaveClass('inline-flex');
|
||||
expect(link).toHaveClass('items-center');
|
||||
});
|
||||
|
||||
it('should work without custom className', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Internationalization', () => {
|
||||
it('should use translation for help text', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
// The mock returns the fallback value
|
||||
const text = screen.getByText('Help');
|
||||
expect(text).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should use translation for title attribute', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveAttribute('title', 'Help');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Integration', () => {
|
||||
it('should render correctly with all props together', () => {
|
||||
render(
|
||||
<HelpButton
|
||||
helpPath="/help/advanced"
|
||||
className="custom-styling"
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toBeInTheDocument();
|
||||
expect(link).toHaveAttribute('href', '/help/advanced');
|
||||
expect(link).toHaveAttribute('title', 'Help');
|
||||
expect(link).toHaveClass('custom-styling');
|
||||
expect(link).toHaveClass('inline-flex');
|
||||
|
||||
const icon = link.querySelector('svg');
|
||||
expect(icon).toBeInTheDocument();
|
||||
|
||||
const text = screen.getByText('Help');
|
||||
expect(text).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should maintain structure with icon and text', () => {
|
||||
render(<HelpButton helpPath="/help" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const link = screen.getByRole('link');
|
||||
const svg = link.querySelector('svg');
|
||||
const span = link.querySelector('span');
|
||||
|
||||
expect(svg).toBeInTheDocument();
|
||||
expect(span).toBeInTheDocument();
|
||||
expect(span).toHaveTextContent('Help');
|
||||
});
|
||||
it('has default styles', () => {
|
||||
renderHelpButton({ helpPath: '/help/test' });
|
||||
const link = screen.getByRole('link');
|
||||
expect(link).toHaveClass('inline-flex');
|
||||
expect(link).toHaveClass('items-center');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,560 +1,93 @@
|
||||
/**
|
||||
* Unit tests for LanguageSelector component
|
||||
*
|
||||
* Tests cover:
|
||||
* - Rendering both dropdown and inline variants
|
||||
* - Current language display
|
||||
* - Dropdown open/close functionality
|
||||
* - Language selection and change
|
||||
* - Available languages display
|
||||
* - Flag display
|
||||
* - Click outside to close dropdown
|
||||
* - Accessibility attributes
|
||||
* - Responsive text hiding
|
||||
* - Custom className prop
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import LanguageSelector from '../LanguageSelector';
|
||||
|
||||
// Mock i18n
|
||||
const mockChangeLanguage = vi.fn();
|
||||
const mockCurrentLanguage = 'en';
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => key,
|
||||
i18n: {
|
||||
language: mockCurrentLanguage,
|
||||
changeLanguage: mockChangeLanguage,
|
||||
language: 'en',
|
||||
changeLanguage: vi.fn(),
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock i18n module with supported languages
|
||||
// Mock i18n module
|
||||
vi.mock('../../i18n', () => ({
|
||||
supportedLanguages: [
|
||||
{ code: 'en', name: 'English', flag: '🇺🇸' },
|
||||
{ code: 'es', name: 'Español', flag: '🇪🇸' },
|
||||
{ code: 'fr', name: 'Français', flag: '🇫🇷' },
|
||||
{ code: 'de', name: 'Deutsch', flag: '🇩🇪' },
|
||||
],
|
||||
}));
|
||||
|
||||
describe('LanguageSelector', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Dropdown Variant (Default)', () => {
|
||||
describe('Rendering', () => {
|
||||
it('should render the language selector button', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button', { expanded: false });
|
||||
expect(button).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display current language name on desktop', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const languageName = screen.getByText('English');
|
||||
expect(languageName).toBeInTheDocument();
|
||||
expect(languageName).toHaveClass('hidden', 'sm:inline');
|
||||
});
|
||||
|
||||
it('should display current language flag by default', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const flag = screen.getByText('🇺🇸');
|
||||
expect(flag).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display Globe icon', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
const svg = button.querySelector('svg');
|
||||
expect(svg).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display ChevronDown icon', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
const chevron = button.querySelector('svg.w-4.h-4.transition-transform');
|
||||
expect(chevron).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should not display flag when showFlag is false', () => {
|
||||
render(<LanguageSelector showFlag={false} />);
|
||||
|
||||
const flag = screen.queryByText('🇺🇸');
|
||||
expect(flag).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should not show dropdown by default', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const dropdown = screen.queryByRole('listbox');
|
||||
expect(dropdown).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Dropdown Open/Close', () => {
|
||||
it('should open dropdown when button clicked', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
const dropdown = screen.getByRole('listbox');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
expect(button).toHaveAttribute('aria-expanded', 'true');
|
||||
});
|
||||
|
||||
it('should close dropdown when button clicked again', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
|
||||
// Open
|
||||
fireEvent.click(button);
|
||||
expect(screen.getByRole('listbox')).toBeInTheDocument();
|
||||
|
||||
// Close
|
||||
fireEvent.click(button);
|
||||
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
|
||||
expect(button).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
|
||||
it('should rotate chevron icon when dropdown is open', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
const chevron = button.querySelector('svg.w-4.h-4.transition-transform');
|
||||
|
||||
// Initially not rotated
|
||||
expect(chevron).not.toHaveClass('rotate-180');
|
||||
|
||||
// Open dropdown
|
||||
fireEvent.click(button);
|
||||
expect(chevron).toHaveClass('rotate-180');
|
||||
});
|
||||
|
||||
it('should close dropdown when clicking outside', async () => {
|
||||
render(
|
||||
<div>
|
||||
<LanguageSelector />
|
||||
<button>Outside Button</button>
|
||||
</div>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { expanded: false });
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(screen.getByRole('listbox')).toBeInTheDocument();
|
||||
|
||||
// Click outside
|
||||
const outsideButton = screen.getByText('Outside Button');
|
||||
fireEvent.mouseDown(outsideButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should not close dropdown when clicking inside dropdown', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
const dropdown = screen.getByRole('listbox');
|
||||
fireEvent.mouseDown(dropdown);
|
||||
|
||||
expect(screen.getByRole('listbox')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Language Selection', () => {
|
||||
it('should display all available languages in dropdown', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(screen.getAllByText('English')).toHaveLength(2); // One in button, one in dropdown
|
||||
expect(screen.getByText('Español')).toBeInTheDocument();
|
||||
expect(screen.getByText('Français')).toBeInTheDocument();
|
||||
expect(screen.getByText('Deutsch')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display flags for all languages in dropdown', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(screen.getAllByText('🇺🇸')).toHaveLength(2); // One in button, one in dropdown
|
||||
expect(screen.getByText('🇪🇸')).toBeInTheDocument();
|
||||
expect(screen.getByText('🇫🇷')).toBeInTheDocument();
|
||||
expect(screen.getByText('🇩🇪')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should mark current language with Check icon', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
const options = screen.getAllByRole('option');
|
||||
const englishOption = options.find(opt => opt.textContent?.includes('English'));
|
||||
|
||||
expect(englishOption).toHaveAttribute('aria-selected', 'true');
|
||||
|
||||
// Check icon should be present
|
||||
const checkIcon = englishOption?.querySelector('svg.w-4.h-4');
|
||||
expect(checkIcon).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should change language when option clicked', async () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
const spanishOption = screen.getAllByRole('option').find(
|
||||
opt => opt.textContent?.includes('Español')
|
||||
);
|
||||
|
||||
fireEvent.click(spanishOption!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockChangeLanguage).toHaveBeenCalledWith('es');
|
||||
});
|
||||
});
|
||||
|
||||
it('should close dropdown after language selection', async () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
const frenchOption = screen.getAllByRole('option').find(
|
||||
opt => opt.textContent?.includes('Français')
|
||||
);
|
||||
|
||||
fireEvent.click(frenchOption!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should highlight selected language with brand color', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
const options = screen.getAllByRole('option');
|
||||
const englishOption = options.find(opt => opt.textContent?.includes('English'));
|
||||
|
||||
expect(englishOption).toHaveClass('bg-brand-50', 'dark:bg-brand-900/20');
|
||||
expect(englishOption).toHaveClass('text-brand-700', 'dark:text-brand-300');
|
||||
});
|
||||
|
||||
it('should not highlight non-selected languages with brand color', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
const options = screen.getAllByRole('option');
|
||||
const spanishOption = options.find(opt => opt.textContent?.includes('Español'));
|
||||
|
||||
expect(spanishOption).toHaveClass('text-gray-700', 'dark:text-gray-300');
|
||||
expect(spanishOption).not.toHaveClass('bg-brand-50');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accessibility', () => {
|
||||
it('should have proper ARIA attributes on button', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(button).toHaveAttribute('aria-haspopup', 'listbox');
|
||||
});
|
||||
|
||||
it('should update aria-expanded when dropdown opens', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toHaveAttribute('aria-expanded', 'false');
|
||||
|
||||
fireEvent.click(button);
|
||||
expect(button).toHaveAttribute('aria-expanded', 'true');
|
||||
});
|
||||
|
||||
it('should have aria-label on listbox', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
const listbox = screen.getByRole('listbox');
|
||||
expect(listbox).toHaveAttribute('aria-label', 'Select language');
|
||||
});
|
||||
|
||||
it('should mark language options as selected correctly', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
const options = screen.getAllByRole('option');
|
||||
const englishOption = options.find(opt => opt.textContent?.includes('English'));
|
||||
const spanishOption = options.find(opt => opt.textContent?.includes('Español'));
|
||||
|
||||
expect(englishOption).toHaveAttribute('aria-selected', 'true');
|
||||
expect(spanishOption).toHaveAttribute('aria-selected', 'false');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Styling', () => {
|
||||
it('should apply default classes to button', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toHaveClass('flex', 'items-center', 'gap-2');
|
||||
expect(button).toHaveClass('px-3', 'py-2');
|
||||
expect(button).toHaveClass('rounded-lg');
|
||||
expect(button).toHaveClass('transition-colors');
|
||||
});
|
||||
|
||||
it('should apply custom className when provided', () => {
|
||||
render(<LanguageSelector className="custom-class" />);
|
||||
|
||||
const container = screen.getByRole('button').parentElement;
|
||||
expect(container).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('should apply dropdown animation classes', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
const dropdown = screen.getByRole('listbox').parentElement;
|
||||
expect(dropdown).toHaveClass('animate-in', 'fade-in', 'slide-in-from-top-2');
|
||||
});
|
||||
|
||||
it('should apply focus ring on button', () => {
|
||||
render(<LanguageSelector />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toHaveClass('focus:outline-none', 'focus:ring-2', 'focus:ring-brand-500');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Inline Variant', () => {
|
||||
describe('Rendering', () => {
|
||||
it('should render inline variant when specified', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
|
||||
// Should show buttons, not a dropdown
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons.length).toBe(4); // One for each language
|
||||
});
|
||||
|
||||
it('should display all languages as separate buttons', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
|
||||
expect(screen.getByText('English')).toBeInTheDocument();
|
||||
expect(screen.getByText('Español')).toBeInTheDocument();
|
||||
expect(screen.getByText('Français')).toBeInTheDocument();
|
||||
expect(screen.getByText('Deutsch')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display flags in inline variant by default', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
|
||||
expect(screen.getByText('🇺🇸')).toBeInTheDocument();
|
||||
expect(screen.getByText('🇪🇸')).toBeInTheDocument();
|
||||
expect(screen.getByText('🇫🇷')).toBeInTheDocument();
|
||||
expect(screen.getByText('🇩🇪')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should not display flags when showFlag is false', () => {
|
||||
render(<LanguageSelector variant="inline" showFlag={false} />);
|
||||
|
||||
expect(screen.queryByText('🇺🇸')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('🇪🇸')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should highlight current language button', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
|
||||
const englishButton = screen.getByRole('button', { name: /English/i });
|
||||
expect(englishButton).toHaveClass('bg-brand-600', 'text-white');
|
||||
});
|
||||
|
||||
it('should not highlight non-selected language buttons', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
|
||||
const spanishButton = screen.getByRole('button', { name: /Español/i });
|
||||
expect(spanishButton).toHaveClass('bg-gray-100', 'text-gray-700');
|
||||
expect(spanishButton).not.toHaveClass('bg-brand-600');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Language Selection', () => {
|
||||
it('should change language when button clicked', async () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
|
||||
const frenchButton = screen.getByRole('button', { name: /Français/i });
|
||||
fireEvent.click(frenchButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockChangeLanguage).toHaveBeenCalledWith('fr');
|
||||
});
|
||||
});
|
||||
|
||||
it('should change language for each available language', async () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
|
||||
const germanButton = screen.getByRole('button', { name: /Deutsch/i });
|
||||
fireEvent.click(germanButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockChangeLanguage).toHaveBeenCalledWith('de');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Styling', () => {
|
||||
it('should apply flex layout classes', () => {
|
||||
const { container } = render(<LanguageSelector variant="inline" />);
|
||||
|
||||
const wrapper = container.firstChild;
|
||||
expect(wrapper).toHaveClass('flex', 'flex-wrap', 'gap-2');
|
||||
});
|
||||
|
||||
it('should apply custom className when provided', () => {
|
||||
const { container } = render(<LanguageSelector variant="inline" className="my-custom-class" />);
|
||||
|
||||
const wrapper = container.firstChild;
|
||||
expect(wrapper).toHaveClass('my-custom-class');
|
||||
});
|
||||
|
||||
it('should apply button styling classes', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
|
||||
const buttons = screen.getAllByRole('button');
|
||||
buttons.forEach(button => {
|
||||
expect(button).toHaveClass('px-3', 'py-1.5', 'rounded-lg', 'text-sm', 'font-medium', 'transition-colors');
|
||||
});
|
||||
});
|
||||
|
||||
it('should apply hover classes to non-selected buttons', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
|
||||
const spanishButton = screen.getByRole('button', { name: /Español/i });
|
||||
expect(spanishButton).toHaveClass('hover:bg-gray-200', 'dark:hover:bg-gray-600');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Integration', () => {
|
||||
it('should render correctly with all dropdown props together', () => {
|
||||
render(
|
||||
<LanguageSelector
|
||||
variant="dropdown"
|
||||
showFlag={true}
|
||||
className="custom-class"
|
||||
/>
|
||||
);
|
||||
|
||||
describe('dropdown variant', () => {
|
||||
it('renders dropdown button', () => {
|
||||
render(<LanguageSelector />);
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toBeInTheDocument();
|
||||
expect(screen.getByText('English')).toBeInTheDocument();
|
||||
expect(screen.getByText('🇺🇸')).toBeInTheDocument();
|
||||
|
||||
const container = button.parentElement;
|
||||
expect(container).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('should render correctly with all inline props together', () => {
|
||||
const { container } = render(
|
||||
<LanguageSelector
|
||||
variant="inline"
|
||||
showFlag={true}
|
||||
className="inline-custom"
|
||||
/>
|
||||
);
|
||||
|
||||
const wrapper = container.firstChild;
|
||||
expect(wrapper).toHaveClass('inline-custom');
|
||||
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons.length).toBe(4);
|
||||
|
||||
it('shows current language flag by default', () => {
|
||||
render(<LanguageSelector />);
|
||||
expect(screen.getByText('🇺🇸')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows current language name on larger screens', () => {
|
||||
render(<LanguageSelector />);
|
||||
expect(screen.getByText('English')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should maintain dropdown functionality across re-renders', () => {
|
||||
const { rerender } = render(<LanguageSelector />);
|
||||
|
||||
it('opens dropdown on click', () => {
|
||||
render(<LanguageSelector />);
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
expect(screen.getByRole('listbox')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
rerender(<LanguageSelector className="updated" />);
|
||||
expect(screen.getByRole('listbox')).toBeInTheDocument();
|
||||
it('shows all languages when open', () => {
|
||||
render(<LanguageSelector />);
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
expect(screen.getByText('Español')).toBeInTheDocument();
|
||||
expect(screen.getByText('Français')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides flag when showFlag is false', () => {
|
||||
render(<LanguageSelector showFlag={false} />);
|
||||
expect(screen.queryByText('🇺🇸')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<LanguageSelector className="custom-class" />);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Edge Cases', () => {
|
||||
it('should handle missing language gracefully', () => {
|
||||
// The component should fall back to the first language if current language is not found
|
||||
render(<LanguageSelector />);
|
||||
|
||||
// Should still render without crashing
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should cleanup event listener on unmount', () => {
|
||||
const { unmount } = render(<LanguageSelector />);
|
||||
|
||||
const removeEventListenerSpy = vi.spyOn(document, 'removeEventListener');
|
||||
unmount();
|
||||
|
||||
expect(removeEventListenerSpy).toHaveBeenCalledWith('mousedown', expect.any(Function));
|
||||
});
|
||||
|
||||
it('should not call changeLanguage when clicking current language', async () => {
|
||||
describe('inline variant', () => {
|
||||
it('renders all language buttons', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons.length).toBe(3);
|
||||
});
|
||||
|
||||
const englishButton = screen.getByRole('button', { name: /English/i });
|
||||
fireEvent.click(englishButton);
|
||||
it('renders language names', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
expect(screen.getByText(/English/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Español/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Français/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockChangeLanguage).toHaveBeenCalledWith('en');
|
||||
});
|
||||
it('highlights current language', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
const englishButton = screen.getByText(/English/).closest('button');
|
||||
expect(englishButton).toHaveClass('bg-brand-600');
|
||||
});
|
||||
|
||||
// Even if clicking the current language, it still calls changeLanguage
|
||||
// This is expected behavior (idempotent)
|
||||
it('shows flags by default', () => {
|
||||
render(<LanguageSelector variant="inline" />);
|
||||
expect(screen.getByText(/🇺🇸/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
201
frontend/src/components/__tests__/LocationSelector.test.tsx
Normal file
201
frontend/src/components/__tests__/LocationSelector.test.tsx
Normal file
@@ -0,0 +1,201 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import React from 'react';
|
||||
import { LocationSelector, useShouldShowLocationSelector } from '../LocationSelector';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
// Mock the useLocations hook
|
||||
vi.mock('../../hooks/useLocations', () => ({
|
||||
useLocations: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useLocations } from '../../hooks/useLocations';
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) =>
|
||||
React.createElement(QueryClientProvider, { client: queryClient }, children);
|
||||
};
|
||||
|
||||
describe('LocationSelector', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders nothing when loading', () => {
|
||||
vi.mocked(useLocations).mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: true,
|
||||
isError: false,
|
||||
} as any);
|
||||
|
||||
const onChange = vi.fn();
|
||||
const { container } = render(
|
||||
<LocationSelector value={null} onChange={onChange} />,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('renders nothing when there is only one location', () => {
|
||||
vi.mocked(useLocations).mockReturnValue({
|
||||
data: [{ id: 1, name: 'Main Office', is_active: true, is_primary: true }],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
} as any);
|
||||
|
||||
const onChange = vi.fn();
|
||||
const { container } = render(
|
||||
<LocationSelector value={null} onChange={onChange} />,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('renders selector when multiple locations exist', () => {
|
||||
vi.mocked(useLocations).mockReturnValue({
|
||||
data: [
|
||||
{ id: 1, name: 'Main Office', is_active: true, is_primary: true },
|
||||
{ id: 2, name: 'Branch Office', is_active: true, is_primary: false },
|
||||
],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
} as any);
|
||||
|
||||
const onChange = vi.fn();
|
||||
render(<LocationSelector value={null} onChange={onChange} />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
expect(screen.getByLabelText('Location')).toBeInTheDocument();
|
||||
expect(screen.getByText('Main Office (Primary)')).toBeInTheDocument();
|
||||
expect(screen.getByText('Branch Office')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows single location when forceShow is true', () => {
|
||||
vi.mocked(useLocations).mockReturnValue({
|
||||
data: [{ id: 1, name: 'Main Office', is_active: true, is_primary: true }],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
} as any);
|
||||
|
||||
const onChange = vi.fn();
|
||||
render(<LocationSelector value={null} onChange={onChange} forceShow />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
expect(screen.getByLabelText('Location')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onChange when selection changes', () => {
|
||||
vi.mocked(useLocations).mockReturnValue({
|
||||
data: [
|
||||
{ id: 1, name: 'Main Office', is_active: true, is_primary: true },
|
||||
{ id: 2, name: 'Branch Office', is_active: true, is_primary: false },
|
||||
],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
} as any);
|
||||
|
||||
const onChange = vi.fn();
|
||||
render(<LocationSelector value={null} onChange={onChange} />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const select = screen.getByLabelText('Location');
|
||||
fireEvent.change(select, { target: { value: '2' } });
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(2);
|
||||
});
|
||||
|
||||
it('marks inactive locations appropriately', () => {
|
||||
vi.mocked(useLocations).mockReturnValue({
|
||||
data: [
|
||||
{ id: 1, name: 'Main Office', is_active: true, is_primary: true },
|
||||
{ id: 2, name: 'Old Branch', is_active: false, is_primary: false },
|
||||
],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
} as any);
|
||||
|
||||
const onChange = vi.fn();
|
||||
render(<LocationSelector value={null} onChange={onChange} includeInactive />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
expect(screen.getByText('Old Branch (Inactive)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays custom label', () => {
|
||||
vi.mocked(useLocations).mockReturnValue({
|
||||
data: [
|
||||
{ id: 1, name: 'Location A', is_active: true, is_primary: false },
|
||||
{ id: 2, name: 'Location B', is_active: true, is_primary: false },
|
||||
],
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
} as any);
|
||||
|
||||
const onChange = vi.fn();
|
||||
render(<LocationSelector value={null} onChange={onChange} label="Select Store" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
expect(screen.getByLabelText('Select Store')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useShouldShowLocationSelector', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('returns false when loading', () => {
|
||||
vi.mocked(useLocations).mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: true,
|
||||
} as any);
|
||||
|
||||
const { result } = renderHook(() => useShouldShowLocationSelector(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
expect(result.current).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when only one location', () => {
|
||||
vi.mocked(useLocations).mockReturnValue({
|
||||
data: [{ id: 1, name: 'Main', is_active: true }],
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
const { result } = renderHook(() => useShouldShowLocationSelector(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
expect(result.current).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true when multiple locations exist', () => {
|
||||
vi.mocked(useLocations).mockReturnValue({
|
||||
data: [
|
||||
{ id: 1, name: 'Main', is_active: true },
|
||||
{ id: 2, name: 'Branch', is_active: true },
|
||||
],
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
const { result } = renderHook(() => useShouldShowLocationSelector(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
expect(result.current).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,534 +1,68 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import MasqueradeBanner from '../MasqueradeBanner';
|
||||
import { User } from '../../types';
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, options?: any) => {
|
||||
const translations: Record<string, string> = {
|
||||
'platform.masquerade.masqueradingAs': 'Masquerading as',
|
||||
'platform.masquerade.loggedInAs': `Logged in as ${options?.name || ''}`,
|
||||
'platform.masquerade.returnTo': `Return to ${options?.name || ''}`,
|
||||
'platform.masquerade.stopMasquerading': 'Stop Masquerading',
|
||||
};
|
||||
return translations[key] || key;
|
||||
t: (key: string, options?: { name?: string }) => {
|
||||
if (options?.name) return `${key} ${options.name}`;
|
||||
return key;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock lucide-react icons
|
||||
vi.mock('lucide-react', () => ({
|
||||
Eye: ({ size }: { size: number }) => <svg data-testid="eye-icon" width={size} height={size} />,
|
||||
XCircle: ({ size }: { size: number }) => <svg data-testid="xcircle-icon" width={size} height={size} />,
|
||||
}));
|
||||
|
||||
describe('MasqueradeBanner', () => {
|
||||
const mockOnStop = vi.fn();
|
||||
|
||||
const effectiveUser: User = {
|
||||
id: '2',
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
role: 'owner',
|
||||
};
|
||||
|
||||
const originalUser: User = {
|
||||
id: '1',
|
||||
name: 'Admin User',
|
||||
email: 'admin@platform.com',
|
||||
role: 'superuser',
|
||||
};
|
||||
|
||||
const previousUser: User = {
|
||||
id: '3',
|
||||
name: 'Manager User',
|
||||
email: 'manager@example.com',
|
||||
role: 'platform_manager',
|
||||
const defaultProps = {
|
||||
effectiveUser: { id: '1', name: 'John Doe', email: 'john@test.com', role: 'staff' as const },
|
||||
originalUser: { id: '2', name: 'Admin User', email: 'admin@test.com', role: 'superuser' as const },
|
||||
previousUser: null,
|
||||
onStop: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('renders the banner with correct structure', () => {
|
||||
const { container } = render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
// Check for main container - it's the first child div
|
||||
const banner = container.firstChild as HTMLElement;
|
||||
expect(banner).toBeInTheDocument();
|
||||
expect(banner).toHaveClass('bg-orange-600', 'text-white');
|
||||
});
|
||||
|
||||
it('displays the Eye icon', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const eyeIcon = screen.getByTestId('eye-icon');
|
||||
expect(eyeIcon).toBeInTheDocument();
|
||||
expect(eyeIcon).toHaveAttribute('width', '18');
|
||||
expect(eyeIcon).toHaveAttribute('height', '18');
|
||||
});
|
||||
|
||||
it('displays the XCircle icon in the button', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const xCircleIcon = screen.getByTestId('xcircle-icon');
|
||||
expect(xCircleIcon).toBeInTheDocument();
|
||||
expect(xCircleIcon).toHaveAttribute('width', '14');
|
||||
expect(xCircleIcon).toHaveAttribute('height', '14');
|
||||
});
|
||||
it('renders effective user name', () => {
|
||||
render(<MasqueradeBanner {...defaultProps} />);
|
||||
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('User Information Display', () => {
|
||||
it('displays the effective user name and role', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
||||
expect(screen.getByText(/owner/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays the original user name', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/Logged in as Admin User/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays masquerading as message', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/Masquerading as/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays different user roles correctly', () => {
|
||||
const staffUser: User = {
|
||||
id: '4',
|
||||
name: 'Staff Member',
|
||||
email: 'staff@example.com',
|
||||
role: 'staff',
|
||||
};
|
||||
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={staffUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Staff Member')).toBeInTheDocument();
|
||||
// Use a more specific query to avoid matching "Staff Member" text
|
||||
expect(screen.getByText(/\(staff\)/i)).toBeInTheDocument();
|
||||
});
|
||||
it('renders effective user role', () => {
|
||||
render(<MasqueradeBanner {...defaultProps} />);
|
||||
// The role is split across elements: "(" + "staff" + ")"
|
||||
expect(screen.getByText(/staff/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('Stop Masquerade Button', () => {
|
||||
it('renders the stop masquerade button when no previous user', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: /Stop Masquerading/i });
|
||||
expect(button).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the return to user button when previous user exists', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={previousUser}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: /Return to Manager User/i });
|
||||
expect(button).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onStop when button is clicked', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: /Stop Masquerading/i });
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(mockOnStop).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('calls onStop when return button is clicked with previous user', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={previousUser}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: /Return to Manager User/i });
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(mockOnStop).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('can be clicked multiple times', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: /Stop Masquerading/i });
|
||||
fireEvent.click(button);
|
||||
fireEvent.click(button);
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(mockOnStop).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
it('renders original user info', () => {
|
||||
render(<MasqueradeBanner {...defaultProps} />);
|
||||
expect(screen.getByText(/Admin User/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('Styling and Visual State', () => {
|
||||
it('has warning/info styling with orange background', () => {
|
||||
const { container } = render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const banner = container.firstChild as HTMLElement;
|
||||
expect(banner).toHaveClass('bg-orange-600');
|
||||
expect(banner).toHaveClass('text-white');
|
||||
});
|
||||
|
||||
it('has proper button styling', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: /Stop Masquerading/i });
|
||||
expect(button).toHaveClass('bg-white');
|
||||
expect(button).toHaveClass('text-orange-600');
|
||||
expect(button).toHaveClass('hover:bg-orange-50');
|
||||
});
|
||||
|
||||
it('has animated pulse effect on Eye icon container', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const eyeIcon = screen.getByTestId('eye-icon');
|
||||
const iconContainer = eyeIcon.closest('div');
|
||||
expect(iconContainer).toHaveClass('animate-pulse');
|
||||
});
|
||||
|
||||
it('has proper layout classes for flexbox', () => {
|
||||
const { container } = render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const banner = container.firstChild as HTMLElement;
|
||||
expect(banner).toHaveClass('flex');
|
||||
expect(banner).toHaveClass('items-center');
|
||||
expect(banner).toHaveClass('justify-between');
|
||||
});
|
||||
|
||||
it('has z-index for proper stacking', () => {
|
||||
const { container } = render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const banner = container.firstChild as HTMLElement;
|
||||
expect(banner).toHaveClass('z-50');
|
||||
expect(banner).toHaveClass('relative');
|
||||
});
|
||||
|
||||
it('has shadow for visual prominence', () => {
|
||||
const { container } = render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const banner = container.firstChild as HTMLElement;
|
||||
expect(banner).toHaveClass('shadow-md');
|
||||
});
|
||||
it('calls onStop when button is clicked', () => {
|
||||
render(<MasqueradeBanner {...defaultProps} />);
|
||||
const stopButton = screen.getByRole('button');
|
||||
fireEvent.click(stopButton);
|
||||
expect(defaultProps.onStop).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('Edge Cases', () => {
|
||||
it('handles users with numeric IDs', () => {
|
||||
const numericIdUser: User = {
|
||||
id: 123,
|
||||
name: 'Numeric User',
|
||||
email: 'numeric@example.com',
|
||||
role: 'customer',
|
||||
};
|
||||
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={numericIdUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Numeric User')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles users with long names', () => {
|
||||
const longNameUser: User = {
|
||||
id: '5',
|
||||
name: 'This Is A Very Long User Name That Should Still Display Properly',
|
||||
email: 'longname@example.com',
|
||||
role: 'manager',
|
||||
};
|
||||
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={longNameUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByText('This Is A Very Long User Name That Should Still Display Properly')
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles all possible user roles', () => {
|
||||
const roles: Array<User['role']> = [
|
||||
'superuser',
|
||||
'platform_manager',
|
||||
'platform_support',
|
||||
'owner',
|
||||
'manager',
|
||||
'staff',
|
||||
'resource',
|
||||
'customer',
|
||||
];
|
||||
|
||||
roles.forEach((role) => {
|
||||
const { unmount } = render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={{ ...effectiveUser, role }}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(new RegExp(role, 'i'))).toBeInTheDocument();
|
||||
unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it('handles previousUser being null', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: /Stop Masquerading/i })).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Return to/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles previousUser being defined', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={previousUser}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: /Return to Manager User/i })).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Stop Masquerading/i)).not.toBeInTheDocument();
|
||||
});
|
||||
it('shows return to previous user text when previousUser exists', () => {
|
||||
const propsWithPrevious = {
|
||||
...defaultProps,
|
||||
previousUser: { id: '3', name: 'Manager', email: 'manager@test.com', role: 'manager' as const },
|
||||
};
|
||||
render(<MasqueradeBanner {...propsWithPrevious} />);
|
||||
expect(screen.getByText(/platform.masquerade.returnTo/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('Accessibility', () => {
|
||||
it('has a clickable button element', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toBeInTheDocument();
|
||||
expect(button.tagName).toBe('BUTTON');
|
||||
});
|
||||
|
||||
it('button has descriptive text', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toHaveTextContent(/Stop Masquerading/i);
|
||||
});
|
||||
|
||||
it('displays user information in semantic HTML', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
const strongElement = screen.getByText('John Doe');
|
||||
expect(strongElement.tagName).toBe('STRONG');
|
||||
});
|
||||
it('shows stop masquerading text when no previousUser', () => {
|
||||
render(<MasqueradeBanner {...defaultProps} />);
|
||||
expect(screen.getByText('platform.masquerade.stopMasquerading')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('Component Integration', () => {
|
||||
it('renders without crashing with minimal props', () => {
|
||||
const minimalEffectiveUser: User = {
|
||||
id: '1',
|
||||
name: 'Test',
|
||||
email: 'test@test.com',
|
||||
role: 'customer',
|
||||
};
|
||||
|
||||
const minimalOriginalUser: User = {
|
||||
id: '2',
|
||||
name: 'Admin',
|
||||
email: 'admin@test.com',
|
||||
role: 'superuser',
|
||||
};
|
||||
|
||||
expect(() =>
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={minimalEffectiveUser}
|
||||
originalUser={minimalOriginalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
)
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('renders all required elements together', () => {
|
||||
render(
|
||||
<MasqueradeBanner
|
||||
effectiveUser={effectiveUser}
|
||||
originalUser={originalUser}
|
||||
previousUser={null}
|
||||
onStop={mockOnStop}
|
||||
/>
|
||||
);
|
||||
|
||||
// Check all major elements are present
|
||||
expect(screen.getByTestId('eye-icon')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('xcircle-icon')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Masquerading as/i)).toBeInTheDocument();
|
||||
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Logged in as Admin User/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button')).toBeInTheDocument();
|
||||
});
|
||||
it('renders with masquerading label', () => {
|
||||
render(<MasqueradeBanner {...defaultProps} />);
|
||||
expect(screen.getByText(/platform.masquerade.masqueradingAs/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
463
frontend/src/components/__tests__/NotificationDropdown.test.tsx
Normal file
463
frontend/src/components/__tests__/NotificationDropdown.test.tsx
Normal file
@@ -0,0 +1,463 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import NotificationDropdown from '../NotificationDropdown';
|
||||
import { Notification } from '../../api/notifications';
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, defaultValue?: string) => defaultValue || key,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock react-router-dom navigate
|
||||
const mockNavigate = vi.fn();
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual('react-router-dom');
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => mockNavigate,
|
||||
};
|
||||
});
|
||||
|
||||
// Mock hooks
|
||||
const mockNotifications: Notification[] = [
|
||||
{
|
||||
id: 1,
|
||||
verb: 'created',
|
||||
read: false,
|
||||
timestamp: new Date().toISOString(),
|
||||
data: {},
|
||||
actor_type: 'user',
|
||||
actor_display: 'John Doe',
|
||||
target_type: 'appointment',
|
||||
target_display: 'Appointment with Jane',
|
||||
target_url: '/appointments/1',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
verb: 'updated',
|
||||
read: true,
|
||||
timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), // 2 hours ago
|
||||
data: {},
|
||||
actor_type: 'user',
|
||||
actor_display: 'Jane Smith',
|
||||
target_type: 'event',
|
||||
target_display: 'Meeting scheduled',
|
||||
target_url: '/events/2',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
verb: 'created a ticket',
|
||||
read: false,
|
||||
timestamp: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(), // 1 day ago
|
||||
data: { ticket_id: '123' },
|
||||
actor_type: 'user',
|
||||
actor_display: 'Support Team',
|
||||
target_type: 'ticket',
|
||||
target_display: 'Ticket #123',
|
||||
target_url: null,
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
verb: 'requested time off',
|
||||
read: false,
|
||||
timestamp: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(), // 10 days ago
|
||||
data: { type: 'time_off_request' },
|
||||
actor_type: 'user',
|
||||
actor_display: 'Bob Johnson',
|
||||
target_type: null,
|
||||
target_display: 'Time off request',
|
||||
target_url: null,
|
||||
},
|
||||
];
|
||||
|
||||
vi.mock('../../hooks/useNotifications', () => ({
|
||||
useNotifications: vi.fn(),
|
||||
useUnreadNotificationCount: vi.fn(),
|
||||
useMarkNotificationRead: vi.fn(),
|
||||
useMarkAllNotificationsRead: vi.fn(),
|
||||
useClearAllNotifications: vi.fn(),
|
||||
}));
|
||||
|
||||
import {
|
||||
useNotifications,
|
||||
useUnreadNotificationCount,
|
||||
useMarkNotificationRead,
|
||||
useMarkAllNotificationsRead,
|
||||
useClearAllNotifications,
|
||||
} from '../../hooks/useNotifications';
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>{children}</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
describe('NotificationDropdown', () => {
|
||||
const mockMarkRead = vi.fn();
|
||||
const mockMarkAllRead = vi.fn();
|
||||
const mockClearAll = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Default mock implementations
|
||||
vi.mocked(useNotifications).mockReturnValue({
|
||||
data: mockNotifications,
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
vi.mocked(useUnreadNotificationCount).mockReturnValue({
|
||||
data: 2,
|
||||
} as any);
|
||||
|
||||
vi.mocked(useMarkNotificationRead).mockReturnValue({
|
||||
mutate: mockMarkRead,
|
||||
isPending: false,
|
||||
} as any);
|
||||
|
||||
vi.mocked(useMarkAllNotificationsRead).mockReturnValue({
|
||||
mutate: mockMarkAllRead,
|
||||
isPending: false,
|
||||
} as any);
|
||||
|
||||
vi.mocked(useClearAllNotifications).mockReturnValue({
|
||||
mutate: mockClearAll,
|
||||
isPending: false,
|
||||
} as any);
|
||||
});
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('renders bell icon button', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
expect(screen.getByRole('button', { name: /open notifications/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays unread count badge when there are unread notifications', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not display badge when unread count is 0', () => {
|
||||
vi.mocked(useUnreadNotificationCount).mockReturnValue({
|
||||
data: 0,
|
||||
} as any);
|
||||
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
expect(screen.queryByText('2')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays "99+" when unread count exceeds 99', () => {
|
||||
vi.mocked(useUnreadNotificationCount).mockReturnValue({
|
||||
data: 150,
|
||||
} as any);
|
||||
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('99+')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render dropdown when closed', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
expect(screen.queryByText('Notifications')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Dropdown interactions', () => {
|
||||
it('opens dropdown when bell icon is clicked', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
expect(screen.getByText('Notifications')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('closes dropdown when close button is clicked', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const closeButtons = screen.getAllByRole('button');
|
||||
const closeButton = closeButtons.find(btn => btn.querySelector('svg'));
|
||||
fireEvent.click(closeButton!);
|
||||
|
||||
expect(screen.queryByText('Notifications')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('closes dropdown when clicking outside', async () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
expect(screen.getByText('Notifications')).toBeInTheDocument();
|
||||
|
||||
// Simulate clicking outside
|
||||
fireEvent.mouseDown(document.body);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Notifications')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Notification list', () => {
|
||||
it('displays all notifications when dropdown is open', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
||||
expect(screen.getByText('Jane Smith')).toBeInTheDocument();
|
||||
expect(screen.getByText('Support Team')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bob Johnson')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays loading state', () => {
|
||||
vi.mocked(useNotifications).mockReturnValue({
|
||||
data: [],
|
||||
isLoading: true,
|
||||
} as any);
|
||||
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
expect(screen.getByText('common.loading')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays empty state when no notifications', () => {
|
||||
vi.mocked(useNotifications).mockReturnValue({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
expect(screen.getByText('No notifications yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('highlights unread notifications', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const notificationButtons = screen.getAllByRole('button');
|
||||
const unreadNotification = notificationButtons.find(btn =>
|
||||
btn.textContent?.includes('John Doe')
|
||||
);
|
||||
|
||||
expect(unreadNotification).toHaveClass('bg-blue-50/50');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Notification actions', () => {
|
||||
it('marks notification as read when clicked', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const notification = screen.getByText('John Doe').closest('button');
|
||||
fireEvent.click(notification!);
|
||||
|
||||
expect(mockMarkRead).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('navigates to target URL when notification is clicked', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const notification = screen.getByText('John Doe').closest('button');
|
||||
fireEvent.click(notification!);
|
||||
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/appointments/1');
|
||||
});
|
||||
|
||||
it('calls onTicketClick for ticket notifications', () => {
|
||||
const mockOnTicketClick = vi.fn();
|
||||
render(<NotificationDropdown onTicketClick={mockOnTicketClick} />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const ticketNotification = screen.getByText('Support Team').closest('button');
|
||||
fireEvent.click(ticketNotification!);
|
||||
|
||||
expect(mockOnTicketClick).toHaveBeenCalledWith('123');
|
||||
});
|
||||
|
||||
it('navigates to time-blocks for time off requests', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const timeOffNotification = screen.getByText('Bob Johnson').closest('button');
|
||||
fireEvent.click(timeOffNotification!);
|
||||
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/time-blocks');
|
||||
});
|
||||
|
||||
it('marks all notifications as read', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
// Find the mark all read button (CheckCheck icon)
|
||||
const buttons = screen.getAllByRole('button');
|
||||
const markAllReadButton = buttons.find(btn =>
|
||||
btn.getAttribute('title')?.includes('Mark all as read')
|
||||
);
|
||||
|
||||
fireEvent.click(markAllReadButton!);
|
||||
expect(mockMarkAllRead).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears all read notifications', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const clearButton = screen.getByText('Clear read');
|
||||
fireEvent.click(clearButton);
|
||||
|
||||
expect(mockClearAll).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('navigates to notifications page when "View all" is clicked', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const viewAllButton = screen.getByText('View all');
|
||||
fireEvent.click(viewAllButton);
|
||||
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/notifications');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Notification icons', () => {
|
||||
it('displays Clock icon for time off requests', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const timeOffNotification = screen.getByText('Bob Johnson').closest('button');
|
||||
const icon = timeOffNotification?.querySelector('svg');
|
||||
|
||||
expect(icon).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays Ticket icon for ticket notifications', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const ticketNotification = screen.getByText('Support Team').closest('button');
|
||||
const icon = ticketNotification?.querySelector('svg');
|
||||
|
||||
expect(icon).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays Calendar icon for event notifications', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const eventNotification = screen.getByText('Jane Smith').closest('button');
|
||||
const icon = eventNotification?.querySelector('svg');
|
||||
|
||||
expect(icon).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Timestamp formatting', () => {
|
||||
it('displays "Just now" for recent notifications', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
// The first notification is just now
|
||||
expect(screen.getByText('Just now')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays relative time for older notifications', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
// Check if notification timestamps are rendered
|
||||
// We have 4 notifications in our mock data, each should have a timestamp
|
||||
const notificationButtons = screen.getAllByRole('button').filter(btn =>
|
||||
btn.textContent?.includes('John Doe') ||
|
||||
btn.textContent?.includes('Jane Smith') ||
|
||||
btn.textContent?.includes('Support Team') ||
|
||||
btn.textContent?.includes('Bob Johnson')
|
||||
);
|
||||
|
||||
expect(notificationButtons.length).toBeGreaterThan(0);
|
||||
// At least one notification should have a timestamp
|
||||
const hasTimestamp = notificationButtons.some(btn => btn.textContent?.match(/Just now|\d+[hmd] ago|\d{1,2}\/\d{1,2}\/\d{4}/));
|
||||
expect(hasTimestamp).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Variants', () => {
|
||||
it('renders with light variant', () => {
|
||||
render(<NotificationDropdown variant="light" />, { wrapper: createWrapper() });
|
||||
const button = screen.getByRole('button', { name: /open notifications/i });
|
||||
expect(button).toHaveClass('text-white/80');
|
||||
});
|
||||
|
||||
it('renders with dark variant (default)', () => {
|
||||
render(<NotificationDropdown variant="dark" />, { wrapper: createWrapper() });
|
||||
const button = screen.getByRole('button', { name: /open notifications/i });
|
||||
expect(button).toHaveClass('text-gray-400');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Loading states', () => {
|
||||
it('disables mark all read button when mutation is pending', () => {
|
||||
vi.mocked(useMarkAllNotificationsRead).mockReturnValue({
|
||||
mutate: mockMarkAllRead,
|
||||
isPending: true,
|
||||
} as any);
|
||||
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const buttons = screen.getAllByRole('button');
|
||||
const markAllReadButton = buttons.find(btn =>
|
||||
btn.getAttribute('title')?.includes('Mark all as read')
|
||||
);
|
||||
|
||||
expect(markAllReadButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables clear all button when mutation is pending', () => {
|
||||
vi.mocked(useClearAllNotifications).mockReturnValue({
|
||||
mutate: mockClearAll,
|
||||
isPending: true,
|
||||
} as any);
|
||||
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
const clearButton = screen.getByText('Clear read');
|
||||
expect(clearButton).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Footer visibility', () => {
|
||||
it('shows footer when there are notifications', () => {
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
expect(screen.getByText('Clear read')).toBeInTheDocument();
|
||||
expect(screen.getByText('View all')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides footer when there are no notifications', () => {
|
||||
vi.mocked(useNotifications).mockReturnValue({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
render(<NotificationDropdown />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /open notifications/i }));
|
||||
|
||||
expect(screen.queryByText('Clear read')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('View all')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
577
frontend/src/components/__tests__/OAuthButtons.test.tsx
Normal file
577
frontend/src/components/__tests__/OAuthButtons.test.tsx
Normal file
@@ -0,0 +1,577 @@
|
||||
/**
|
||||
* Unit tests for OAuthButtons component
|
||||
*
|
||||
* Tests OAuth provider buttons for social login.
|
||||
* Covers:
|
||||
* - Rendering providers from API
|
||||
* - Button clicks and OAuth initiation
|
||||
* - Loading states (initial load and button clicks)
|
||||
* - Provider-specific styling (colors, icons)
|
||||
* - Disabled state
|
||||
* - Error handling
|
||||
* - Empty state (no providers)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import OAuthButtons from '../OAuthButtons';
|
||||
|
||||
// Mock hooks
|
||||
const mockUseOAuthProviders = vi.fn();
|
||||
const mockUseInitiateOAuth = vi.fn();
|
||||
|
||||
vi.mock('../../hooks/useOAuth', () => ({
|
||||
useOAuthProviders: () => mockUseOAuthProviders(),
|
||||
useInitiateOAuth: () => mockUseInitiateOAuth(),
|
||||
}));
|
||||
|
||||
// Helper to wrap component with QueryClient
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
describe('OAuthButtons', () => {
|
||||
const mockMutate = vi.fn();
|
||||
const mockOnSuccess = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockUseInitiateOAuth.mockReturnValue({
|
||||
mutate: mockMutate,
|
||||
isPending: false,
|
||||
variables: null,
|
||||
});
|
||||
});
|
||||
|
||||
describe('Loading State', () => {
|
||||
it('should show loading spinner while fetching providers', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: true,
|
||||
});
|
||||
|
||||
const { container } = render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
// Look for the spinner SVG element with animate-spin class
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should not show providers while loading', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: true,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
expect(screen.queryByRole('button', { name: /continue with/i })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Empty State', () => {
|
||||
it('should render nothing when no providers are available', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
const { container } = render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render nothing when providers data is null', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: null,
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
const { container } = render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Provider Rendering', () => {
|
||||
it('should render Google provider button', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with google/i });
|
||||
expect(button).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render multiple provider buttons', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [
|
||||
{ name: 'google', display_name: 'Google' },
|
||||
{ name: 'facebook', display_name: 'Facebook' },
|
||||
{ name: 'apple', display_name: 'Apple' },
|
||||
],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
expect(screen.getByRole('button', { name: /continue with google/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /continue with facebook/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /continue with apple/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should apply Google-specific styling (white bg, border)', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with google/i });
|
||||
expect(button).toHaveClass('bg-white', 'text-gray-900', 'border-gray-300');
|
||||
});
|
||||
|
||||
it('should apply Apple-specific styling (black bg)', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'apple', display_name: 'Apple' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with apple/i });
|
||||
expect(button).toHaveClass('bg-black', 'text-white');
|
||||
});
|
||||
|
||||
it('should apply Facebook-specific styling (blue bg)', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'facebook', display_name: 'Facebook' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with facebook/i });
|
||||
expect(button).toHaveClass('bg-[#1877F2]', 'text-white');
|
||||
});
|
||||
|
||||
it('should apply LinkedIn-specific styling', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'linkedin', display_name: 'LinkedIn' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with linkedin/i });
|
||||
expect(button).toHaveClass('bg-[#0A66C2]', 'text-white');
|
||||
});
|
||||
|
||||
it('should render unknown provider with fallback styling', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'custom_provider', display_name: 'Custom Provider' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with custom provider/i });
|
||||
expect(button).toBeInTheDocument();
|
||||
expect(button).toHaveClass('bg-gray-600', 'text-white');
|
||||
});
|
||||
|
||||
it('should display provider icons', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [
|
||||
{ name: 'google', display_name: 'Google' },
|
||||
{ name: 'facebook', display_name: 'Facebook' },
|
||||
],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
// Icons should be present (rendered as text in config)
|
||||
expect(screen.getByText('G')).toBeInTheDocument(); // Google icon
|
||||
expect(screen.getByText('f')).toBeInTheDocument(); // Facebook icon
|
||||
});
|
||||
});
|
||||
|
||||
describe('Button Clicks', () => {
|
||||
it('should call OAuth initiation when button is clicked', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with google/i });
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(mockMutate).toHaveBeenCalledWith('google', expect.any(Object));
|
||||
});
|
||||
|
||||
it('should call onSuccess callback after successful OAuth initiation', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
mockMutate.mockImplementation((provider, { onSuccess }) => {
|
||||
onSuccess?.();
|
||||
});
|
||||
|
||||
render(<OAuthButtons onSuccess={mockOnSuccess} />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with google/i });
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(mockOnSuccess).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should handle multiple provider clicks', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [
|
||||
{ name: 'google', display_name: 'Google' },
|
||||
{ name: 'facebook', display_name: 'Facebook' },
|
||||
],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const googleButton = screen.getByRole('button', { name: /continue with google/i });
|
||||
const facebookButton = screen.getByRole('button', { name: /continue with facebook/i });
|
||||
|
||||
fireEvent.click(googleButton);
|
||||
expect(mockMutate).toHaveBeenCalledWith('google', expect.any(Object));
|
||||
|
||||
fireEvent.click(facebookButton);
|
||||
expect(mockMutate).toHaveBeenCalledWith('facebook', expect.any(Object));
|
||||
});
|
||||
|
||||
it('should not initiate OAuth when button is disabled', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons disabled={true} />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with google/i });
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(mockMutate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not initiate OAuth when another button is pending', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
mockUseInitiateOAuth.mockReturnValue({
|
||||
mutate: mockMutate,
|
||||
isPending: true,
|
||||
variables: 'google',
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /connecting/i });
|
||||
fireEvent.click(button);
|
||||
|
||||
// Should not call mutate again
|
||||
expect(mockMutate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Loading State During OAuth', () => {
|
||||
it('should show loading state on clicked button', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
mockUseInitiateOAuth.mockReturnValue({
|
||||
mutate: mockMutate,
|
||||
isPending: true,
|
||||
variables: 'google',
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
expect(screen.getByText(/connecting/i)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/continue with google/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show spinner icon during loading', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
mockUseInitiateOAuth.mockReturnValue({
|
||||
mutate: mockMutate,
|
||||
isPending: true,
|
||||
variables: 'google',
|
||||
});
|
||||
|
||||
const { container } = render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
// Loader2 icon should be rendered
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should only show loading on the clicked button', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [
|
||||
{ name: 'google', display_name: 'Google' },
|
||||
{ name: 'facebook', display_name: 'Facebook' },
|
||||
],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
mockUseInitiateOAuth.mockReturnValue({
|
||||
mutate: mockMutate,
|
||||
isPending: true,
|
||||
variables: 'google',
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
// Google button should show loading
|
||||
expect(screen.getByText(/connecting/i)).toBeInTheDocument();
|
||||
|
||||
// Facebook button should still show normal text
|
||||
expect(screen.getByText(/continue with facebook/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Disabled State', () => {
|
||||
it('should disable all buttons when disabled prop is true', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [
|
||||
{ name: 'google', display_name: 'Google' },
|
||||
{ name: 'facebook', display_name: 'Facebook' },
|
||||
],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons disabled={true} />, { wrapper: createWrapper() });
|
||||
|
||||
const googleButton = screen.getByRole('button', { name: /continue with google/i });
|
||||
const facebookButton = screen.getByRole('button', { name: /continue with facebook/i });
|
||||
|
||||
expect(googleButton).toBeDisabled();
|
||||
expect(facebookButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should apply disabled styling when disabled', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons disabled={true} />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with google/i });
|
||||
expect(button).toHaveClass('disabled:opacity-50', 'disabled:cursor-not-allowed');
|
||||
});
|
||||
|
||||
it('should disable all buttons during OAuth pending', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [
|
||||
{ name: 'google', display_name: 'Google' },
|
||||
{ name: 'facebook', display_name: 'Facebook' },
|
||||
],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
mockUseInitiateOAuth.mockReturnValue({
|
||||
mutate: mockMutate,
|
||||
isPending: true,
|
||||
variables: 'google',
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const buttons = screen.getAllByRole('button');
|
||||
buttons.forEach(button => {
|
||||
expect(button).toBeDisabled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('should log error on OAuth initiation failure', () => {
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
const error = new Error('OAuth error');
|
||||
mockMutate.mockImplementation((provider, { onError }) => {
|
||||
onError?.(error);
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with google/i });
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('OAuth initiation error:', error);
|
||||
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Provider Variants', () => {
|
||||
it('should render Microsoft provider', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'microsoft', display_name: 'Microsoft' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with microsoft/i });
|
||||
expect(button).toBeInTheDocument();
|
||||
expect(button).toHaveClass('bg-[#00A4EF]');
|
||||
});
|
||||
|
||||
it('should render X (Twitter) provider', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'x', display_name: 'X' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with x/i });
|
||||
expect(button).toBeInTheDocument();
|
||||
expect(button).toHaveClass('bg-black');
|
||||
});
|
||||
|
||||
it('should render Twitch provider', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'twitch', display_name: 'Twitch' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with twitch/i });
|
||||
expect(button).toBeInTheDocument();
|
||||
expect(button).toHaveClass('bg-[#9146FF]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Button Styling', () => {
|
||||
it('should have consistent button styling', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with google/i });
|
||||
expect(button).toHaveClass(
|
||||
'w-full',
|
||||
'flex',
|
||||
'items-center',
|
||||
'justify-center',
|
||||
'rounded-lg',
|
||||
'shadow-sm'
|
||||
);
|
||||
});
|
||||
|
||||
it('should have hover transition styles', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with google/i });
|
||||
expect(button).toHaveClass('transition-all', 'duration-200');
|
||||
});
|
||||
|
||||
it('should have focus ring styles', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const button = screen.getByRole('button', { name: /continue with google/i });
|
||||
expect(button).toHaveClass('focus:outline-none', 'focus:ring-2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accessibility', () => {
|
||||
it('should have button role for all providers', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [
|
||||
{ name: 'google', display_name: 'Google' },
|
||||
{ name: 'facebook', display_name: 'Facebook' },
|
||||
],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should have descriptive button text', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
expect(screen.getByRole('button', { name: /continue with google/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should indicate loading state to screen readers', () => {
|
||||
mockUseOAuthProviders.mockReturnValue({
|
||||
data: [{ name: 'google', display_name: 'Google' }],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
mockUseInitiateOAuth.mockReturnValue({
|
||||
mutate: mockMutate,
|
||||
isPending: true,
|
||||
variables: 'google',
|
||||
});
|
||||
|
||||
render(<OAuthButtons />, { wrapper: createWrapper() });
|
||||
|
||||
expect(screen.getByText(/connecting/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
827
frontend/src/components/__tests__/OnboardingWizard.test.tsx
Normal file
827
frontend/src/components/__tests__/OnboardingWizard.test.tsx
Normal file
@@ -0,0 +1,827 @@
|
||||
/**
|
||||
* Unit tests for OnboardingWizard component
|
||||
*
|
||||
* Tests the multi-step onboarding wizard for new businesses.
|
||||
* Covers:
|
||||
* - Step navigation (welcome -> stripe -> complete)
|
||||
* - Step indicator visualization
|
||||
* - Welcome step rendering and buttons
|
||||
* - Stripe Connect integration step
|
||||
* - Completion step
|
||||
* - Skip functionality
|
||||
* - Auto-advance on Stripe connection
|
||||
* - URL parameter handling (OAuth callback)
|
||||
* - Loading states
|
||||
* - Business update on completion
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { BrowserRouter, useSearchParams } from 'react-router-dom';
|
||||
import OnboardingWizard from '../OnboardingWizard';
|
||||
import { Business } from '../../types';
|
||||
|
||||
// Mock hooks
|
||||
const mockUsePaymentConfig = vi.fn();
|
||||
const mockUseUpdateBusiness = vi.fn();
|
||||
const mockSetSearchParams = vi.fn();
|
||||
const mockSearchParams = new URLSearchParams();
|
||||
|
||||
vi.mock('../../hooks/usePayments', () => ({
|
||||
usePaymentConfig: () => mockUsePaymentConfig(),
|
||||
}));
|
||||
|
||||
vi.mock('../../hooks/useBusiness', () => ({
|
||||
useUpdateBusiness: () => mockUseUpdateBusiness(),
|
||||
}));
|
||||
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual('react-router-dom');
|
||||
return {
|
||||
...actual,
|
||||
useSearchParams: () => [mockSearchParams, mockSetSearchParams],
|
||||
};
|
||||
});
|
||||
|
||||
// Mock ConnectOnboardingEmbed component
|
||||
vi.mock('../ConnectOnboardingEmbed', () => ({
|
||||
default: ({ onComplete, onError }: any) => (
|
||||
<div data-testid="connect-embed">
|
||||
<button onClick={() => onComplete()}>Complete Embed</button>
|
||||
<button onClick={() => onError('Test error')}>Trigger Error</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, params?: Record<string, unknown>) => {
|
||||
const translations: Record<string, string> = {
|
||||
'onboarding.steps.welcome': 'Welcome',
|
||||
'onboarding.steps.payments': 'Payments',
|
||||
'onboarding.steps.complete': 'Complete',
|
||||
'onboarding.welcome.title': `Welcome to ${params?.businessName}!`,
|
||||
'onboarding.welcome.subtitle': "Let's get you set up",
|
||||
'onboarding.welcome.whatsIncluded': "What's Included",
|
||||
'onboarding.welcome.connectStripe': 'Connect to Stripe',
|
||||
'onboarding.welcome.automaticPayouts': 'Automatic payouts',
|
||||
'onboarding.welcome.pciCompliance': 'PCI compliance',
|
||||
'onboarding.welcome.getStarted': 'Get Started',
|
||||
'onboarding.welcome.skip': 'Skip for now',
|
||||
'onboarding.stripe.title': 'Connect Stripe',
|
||||
'onboarding.stripe.subtitle': `Accept payments with your ${params?.plan} plan`,
|
||||
'onboarding.stripe.checkingStatus': 'Checking status...',
|
||||
'onboarding.stripe.connected.title': 'Connected!',
|
||||
'onboarding.stripe.connected.subtitle': 'Your account is ready',
|
||||
'onboarding.stripe.continue': 'Continue',
|
||||
'onboarding.stripe.doLater': 'Do this later',
|
||||
'onboarding.complete.title': "You're all set!",
|
||||
'onboarding.complete.subtitle': 'Ready to start',
|
||||
'onboarding.complete.checklist.accountCreated': 'Account created',
|
||||
'onboarding.complete.checklist.stripeConfigured': 'Stripe configured',
|
||||
'onboarding.complete.checklist.readyForPayments': 'Ready for payments',
|
||||
'onboarding.complete.goToDashboard': 'Go to Dashboard',
|
||||
'onboarding.skipForNow': 'Skip for now',
|
||||
};
|
||||
return translations[key] || key;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Test data factory
|
||||
const createMockBusiness = (overrides?: Partial<Business>): Business => ({
|
||||
id: '1',
|
||||
name: 'Test Business',
|
||||
subdomain: 'testbiz',
|
||||
primaryColor: '#3B82F6',
|
||||
secondaryColor: '#1E40AF',
|
||||
whitelabelEnabled: false,
|
||||
paymentsEnabled: false,
|
||||
requirePaymentMethodToBook: false,
|
||||
cancellationWindowHours: 24,
|
||||
lateCancellationFeePercent: 50,
|
||||
plan: 'Professional',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
// Helper to wrap component with providers
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>{children}</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
describe('OnboardingWizard', () => {
|
||||
const mockOnComplete = vi.fn();
|
||||
const mockOnSkip = vi.fn();
|
||||
const mockRefetch = vi.fn();
|
||||
const mockMutateAsync = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockSearchParams.delete('connect');
|
||||
|
||||
mockUsePaymentConfig.mockReturnValue({
|
||||
data: {
|
||||
connect_account: null,
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
mockUseUpdateBusiness.mockReturnValue({
|
||||
mutateAsync: mockMutateAsync,
|
||||
isPending: false,
|
||||
});
|
||||
});
|
||||
|
||||
describe('Modal Rendering', () => {
|
||||
it('should render modal overlay', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
const { container } = render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
// Modal has the fixed class for overlay
|
||||
const modal = container.querySelector('.fixed');
|
||||
expect(modal).toBeInTheDocument();
|
||||
expect(modal).toHaveClass('inset-0');
|
||||
});
|
||||
|
||||
it('should render close button', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const closeButton = screen.getAllByRole('button').find(btn =>
|
||||
btn.querySelector('svg')
|
||||
);
|
||||
expect(closeButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should have scrollable content', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
const { container } = render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const modal = container.querySelector('.overflow-auto');
|
||||
expect(modal).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Step Indicator', () => {
|
||||
it('should render step indicator with 3 steps', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
const { container } = render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const stepCircles = container.querySelectorAll('.rounded-full.w-8.h-8');
|
||||
expect(stepCircles.length).toBe(3);
|
||||
});
|
||||
|
||||
it('should highlight current step', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
const { container } = render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const activeStep = container.querySelector('.bg-blue-600');
|
||||
expect(activeStep).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show completed steps with checkmark', async () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
const { container } = render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
// Move to next step
|
||||
const getStartedButton = screen.getByRole('button', { name: /get started/i });
|
||||
fireEvent.click(getStartedButton);
|
||||
|
||||
// First step should show green background after navigation
|
||||
await waitFor(() => {
|
||||
const completedStep = container.querySelector('.bg-green-500');
|
||||
expect(completedStep).toBeTruthy();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Welcome Step', () => {
|
||||
it('should render welcome step by default', () => {
|
||||
const business = createMockBusiness({ name: 'Test Business' });
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
expect(screen.getByText(/welcome to test business/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render sparkles icon', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
const { container } = render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const iconCircle = container.querySelector('.bg-gradient-to-br.from-blue-500');
|
||||
expect(iconCircle).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show features list', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
expect(screen.getByText(/connect to stripe/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/automatic payouts/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/pci compliance/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render Get Started button', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: /get started/i });
|
||||
expect(button).toBeInTheDocument();
|
||||
expect(button).toHaveClass('bg-blue-600');
|
||||
});
|
||||
|
||||
it('should render Skip button', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
// Look for the skip button with exact text (not the close button with title)
|
||||
const skipButtons = screen.getAllByRole('button', { name: /skip for now/i });
|
||||
expect(skipButtons.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should advance to stripe step on Get Started click', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const getStartedButton = screen.getByRole('button', { name: /get started/i });
|
||||
fireEvent.click(getStartedButton);
|
||||
|
||||
expect(screen.getByText(/connect stripe/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Stripe Connect Step', () => {
|
||||
beforeEach(() => {
|
||||
// Start at Stripe step
|
||||
const business = createMockBusiness();
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
const getStartedButton = screen.getByRole('button', { name: /get started/i });
|
||||
fireEvent.click(getStartedButton);
|
||||
});
|
||||
|
||||
it('should render Stripe step after welcome', () => {
|
||||
expect(screen.getByText(/connect stripe/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show loading while checking status', () => {
|
||||
mockUsePaymentConfig.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: true,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
const business = createMockBusiness();
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
// Navigate to stripe step
|
||||
fireEvent.click(screen.getByRole('button', { name: /get started/i }));
|
||||
|
||||
expect(screen.getByText(/checking status/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render ConnectOnboardingEmbed when not connected', () => {
|
||||
expect(screen.getByTestId('connect-embed')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show success message when already connected', () => {
|
||||
mockUsePaymentConfig.mockReturnValue({
|
||||
data: {
|
||||
connect_account: {
|
||||
status: 'active',
|
||||
charges_enabled: true,
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
const business = createMockBusiness();
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /get started/i }));
|
||||
|
||||
// Component auto-advances to complete step when already connected
|
||||
expect(screen.getByText(/you're all set!/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render Do This Later button', () => {
|
||||
expect(screen.getByRole('button', { name: /do this later/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle embedded onboarding completion', async () => {
|
||||
const completeButton = screen.getByText('Complete Embed');
|
||||
fireEvent.click(completeButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRefetch).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle embedded onboarding error', () => {
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
const errorButton = screen.getByText('Trigger Error');
|
||||
fireEvent.click(errorButton);
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('Embedded onboarding error:', 'Test error');
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Complete Step', () => {
|
||||
it('should render complete step when Stripe is connected', () => {
|
||||
mockUsePaymentConfig.mockReturnValue({
|
||||
data: {
|
||||
connect_account: {
|
||||
status: 'active',
|
||||
charges_enabled: true,
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
const business = createMockBusiness();
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
// Navigate to stripe step - will auto-advance to complete since connected
|
||||
fireEvent.click(screen.getByRole('button', { name: /get started/i }));
|
||||
|
||||
expect(screen.getByText(/you're all set!/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show completion checklist', () => {
|
||||
mockUsePaymentConfig.mockReturnValue({
|
||||
data: {
|
||||
connect_account: {
|
||||
status: 'active',
|
||||
charges_enabled: true,
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
const business = createMockBusiness();
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /get started/i }));
|
||||
|
||||
expect(screen.getByText(/account created/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/stripe configured/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/ready for payments/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render Go to Dashboard button', () => {
|
||||
mockUsePaymentConfig.mockReturnValue({
|
||||
data: {
|
||||
connect_account: {
|
||||
status: 'active',
|
||||
charges_enabled: true,
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
const business = createMockBusiness();
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /get started/i }));
|
||||
|
||||
expect(screen.getByRole('button', { name: /go to dashboard/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call onComplete when dashboard button clicked', async () => {
|
||||
mockMutateAsync.mockResolvedValue({});
|
||||
mockUsePaymentConfig.mockReturnValue({
|
||||
data: {
|
||||
connect_account: {
|
||||
status: 'active',
|
||||
charges_enabled: true,
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
const business = createMockBusiness();
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /get started/i }));
|
||||
|
||||
const dashboardButton = screen.getByRole('button', { name: /go to dashboard/i });
|
||||
fireEvent.click(dashboardButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockMutateAsync).toHaveBeenCalledWith({ initialSetupComplete: true });
|
||||
expect(mockOnComplete).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Skip Functionality', () => {
|
||||
it('should call onSkip when skip button clicked on welcome', async () => {
|
||||
mockMutateAsync.mockResolvedValue({});
|
||||
const business = createMockBusiness();
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
onSkip={mockOnSkip}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
// Find the text-based skip button (not the X close button)
|
||||
const skipButtons = screen.getAllByRole('button', { name: /skip for now/i });
|
||||
const skipButton = skipButtons.find(btn => btn.textContent?.includes('Skip for now'));
|
||||
if (skipButton) {
|
||||
fireEvent.click(skipButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockMutateAsync).toHaveBeenCalledWith({ initialSetupComplete: true });
|
||||
expect(mockOnSkip).toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('should call onComplete when no onSkip provided', async () => {
|
||||
mockMutateAsync.mockResolvedValue({});
|
||||
const business = createMockBusiness();
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const skipButtons = screen.getAllByRole('button', { name: /skip for now/i });
|
||||
const skipButton = skipButtons.find(btn => btn.textContent?.includes('Skip for now'));
|
||||
if (skipButton) {
|
||||
fireEvent.click(skipButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockOnComplete).toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('should update business setup complete flag on skip', async () => {
|
||||
mockMutateAsync.mockResolvedValue({});
|
||||
const business = createMockBusiness();
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const skipButtons = screen.getAllByRole('button', { name: /skip for now/i });
|
||||
const skipButton = skipButtons.find(btn => btn.textContent?.includes('Skip for now'));
|
||||
if (skipButton) {
|
||||
fireEvent.click(skipButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockMutateAsync).toHaveBeenCalledWith({ initialSetupComplete: true });
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('should close wizard when X button clicked', async () => {
|
||||
mockMutateAsync.mockResolvedValue({});
|
||||
const business = createMockBusiness();
|
||||
|
||||
const { container } = render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
// Find X button (close button)
|
||||
const closeButtons = screen.getAllByRole('button');
|
||||
const xButton = closeButtons.find(btn => btn.querySelector('svg') && !btn.textContent?.trim());
|
||||
|
||||
if (xButton) {
|
||||
fireEvent.click(xButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockMutateAsync).toHaveBeenCalled();
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Auto-advance on Stripe Connection', () => {
|
||||
it('should auto-advance to complete when Stripe connects', async () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
// Start not connected
|
||||
mockUsePaymentConfig.mockReturnValue({
|
||||
data: {
|
||||
connect_account: null,
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
const { rerender } = render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
// Navigate to stripe step
|
||||
fireEvent.click(screen.getByRole('button', { name: /get started/i }));
|
||||
|
||||
// Simulate Stripe connection
|
||||
mockUsePaymentConfig.mockReturnValue({
|
||||
data: {
|
||||
connect_account: {
|
||||
status: 'active',
|
||||
charges_enabled: true,
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
rerender(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/you're all set!/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('URL Parameter Handling', () => {
|
||||
it('should handle connect=complete query parameter', () => {
|
||||
mockSearchParams.set('connect', 'complete');
|
||||
|
||||
const business = createMockBusiness();
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
expect(mockRefetch).toHaveBeenCalled();
|
||||
expect(mockSetSearchParams).toHaveBeenCalledWith({});
|
||||
});
|
||||
|
||||
it('should handle connect=refresh query parameter', () => {
|
||||
mockSearchParams.set('connect', 'refresh');
|
||||
|
||||
const business = createMockBusiness();
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
expect(mockRefetch).toHaveBeenCalled();
|
||||
expect(mockSetSearchParams).toHaveBeenCalledWith({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Loading States', () => {
|
||||
it('should disable dashboard button while updating', () => {
|
||||
mockUseUpdateBusiness.mockReturnValue({
|
||||
mutateAsync: mockMutateAsync,
|
||||
isPending: true,
|
||||
});
|
||||
|
||||
mockUsePaymentConfig.mockReturnValue({
|
||||
data: {
|
||||
connect_account: {
|
||||
status: 'active',
|
||||
charges_enabled: true,
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
const business = createMockBusiness();
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /get started/i }));
|
||||
|
||||
// Dashboard button should be disabled while updating
|
||||
const buttons = screen.getAllByRole('button');
|
||||
const dashboardButton = buttons.find(btn => btn.textContent?.includes('Dashboard') || btn.querySelector('.animate-spin'));
|
||||
if (dashboardButton) {
|
||||
expect(dashboardButton).toBeDisabled();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accessibility', () => {
|
||||
it('should have proper modal structure', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
const { container } = render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
// Modal overlay with fixed positioning
|
||||
const modalOverlay = container.querySelector('.fixed.z-50');
|
||||
expect(modalOverlay).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should have semantic headings', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
expect(screen.getByRole('heading', { level: 2 })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should have accessible buttons', () => {
|
||||
const business = createMockBusiness();
|
||||
|
||||
render(
|
||||
<OnboardingWizard
|
||||
business={business}
|
||||
onComplete={mockOnComplete}
|
||||
/>,
|
||||
{ wrapper: createWrapper() }
|
||||
);
|
||||
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
481
frontend/src/components/__tests__/ResourceCalendar.test.tsx
Normal file
481
frontend/src/components/__tests__/ResourceCalendar.test.tsx
Normal file
@@ -0,0 +1,481 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import ResourceCalendar from '../ResourceCalendar';
|
||||
import { Appointment } from '../../types';
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, defaultValue?: string) => defaultValue || key,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock Portal component
|
||||
vi.mock('../Portal', () => ({
|
||||
default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
}));
|
||||
|
||||
// Mock date-fns to control time-based tests
|
||||
vi.mock('date-fns', async () => {
|
||||
const actual = await vi.importActual('date-fns');
|
||||
return {
|
||||
...actual,
|
||||
};
|
||||
});
|
||||
|
||||
// Use today's date for appointments so they show up in the calendar
|
||||
const today = new Date();
|
||||
today.setHours(10, 0, 0, 0);
|
||||
|
||||
const mockAppointments: Appointment[] = [
|
||||
{
|
||||
id: '1',
|
||||
resourceId: 'resource-1',
|
||||
customerId: 'customer-1',
|
||||
customerName: 'John Doe',
|
||||
serviceId: 'service-1',
|
||||
startTime: new Date(today.getTime()),
|
||||
durationMinutes: 60,
|
||||
status: 'SCHEDULED',
|
||||
notes: 'First appointment',
|
||||
depositAmount: null,
|
||||
depositTransactionId: '',
|
||||
finalPrice: null,
|
||||
finalChargeTransactionId: '',
|
||||
isVariablePricing: false,
|
||||
remainingBalance: null,
|
||||
overpaidAmount: null,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
resourceId: 'resource-1',
|
||||
customerId: 'customer-2',
|
||||
customerName: 'Jane Smith',
|
||||
serviceId: 'service-2',
|
||||
startTime: new Date(today.getTime() + 4.5 * 60 * 60 * 1000), // 14:30
|
||||
durationMinutes: 90,
|
||||
status: 'SCHEDULED',
|
||||
notes: 'Second appointment',
|
||||
depositAmount: null,
|
||||
depositTransactionId: '',
|
||||
finalPrice: null,
|
||||
finalChargeTransactionId: '',
|
||||
isVariablePricing: false,
|
||||
remainingBalance: null,
|
||||
overpaidAmount: null,
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
resourceId: 'resource-2',
|
||||
customerId: 'customer-3',
|
||||
customerName: 'Bob Johnson',
|
||||
serviceId: 'service-1',
|
||||
startTime: new Date(today.getTime() + 1 * 60 * 60 * 1000), // 11:00
|
||||
durationMinutes: 45,
|
||||
status: 'SCHEDULED',
|
||||
notes: 'Different resource',
|
||||
depositAmount: null,
|
||||
depositTransactionId: '',
|
||||
finalPrice: null,
|
||||
finalChargeTransactionId: '',
|
||||
isVariablePricing: false,
|
||||
remainingBalance: null,
|
||||
overpaidAmount: null,
|
||||
},
|
||||
];
|
||||
|
||||
vi.mock('../../hooks/useAppointments', () => ({
|
||||
useAppointments: vi.fn(),
|
||||
useUpdateAppointment: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useAppointments, useUpdateAppointment } from '../../hooks/useAppointments';
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
describe('ResourceCalendar', () => {
|
||||
const mockOnClose = vi.fn();
|
||||
const mockUpdateMutate = vi.fn();
|
||||
|
||||
const defaultProps = {
|
||||
resourceId: 'resource-1',
|
||||
resourceName: 'Dr. Smith',
|
||||
onClose: mockOnClose,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
vi.mocked(useAppointments).mockReturnValue({
|
||||
data: mockAppointments,
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
vi.mocked(useUpdateAppointment).mockReturnValue({
|
||||
mutate: mockUpdateMutate,
|
||||
mutateAsync: vi.fn(),
|
||||
} as any);
|
||||
});
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('renders calendar modal', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('Dr. Smith Calendar')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays close button', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
const closeButtons = screen.getAllByRole('button');
|
||||
const closeButton = closeButtons.find(btn => btn.querySelector('svg'));
|
||||
expect(closeButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onClose when close button is clicked', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
const closeButtons = screen.getAllByRole('button');
|
||||
const closeButton = closeButtons.find(btn => btn.querySelector('svg'));
|
||||
fireEvent.click(closeButton!);
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('displays resource name in title', () => {
|
||||
render(<ResourceCalendar {...defaultProps} resourceName="Conference Room A" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
expect(screen.getByText('Conference Room A Calendar')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('View modes', () => {
|
||||
it('renders day view by default', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
const dayButton = screen.getByRole('button', { name: /^day$/i });
|
||||
expect(dayButton).toHaveClass('bg-white');
|
||||
});
|
||||
|
||||
it('switches to week view when week button is clicked', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
const weekButton = screen.getByRole('button', { name: /^week$/i });
|
||||
fireEvent.click(weekButton);
|
||||
expect(weekButton).toHaveClass('bg-white');
|
||||
});
|
||||
|
||||
it('switches to month view when month button is clicked', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
const monthButton = screen.getByRole('button', { name: /^month$/i });
|
||||
fireEvent.click(monthButton);
|
||||
expect(monthButton).toHaveClass('bg-white');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Navigation', () => {
|
||||
it('displays Today button', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByRole('button', { name: /today/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays previous and next navigation buttons', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
const buttons = screen.getAllByRole('button');
|
||||
const navButtons = buttons.filter(btn => btn.querySelector('svg'));
|
||||
expect(navButtons.length).toBeGreaterThan(2);
|
||||
});
|
||||
|
||||
it('navigates to previous day in day view', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
const buttons = screen.getAllByRole('button');
|
||||
const prevButton = buttons.find(btn => {
|
||||
const svg = btn.querySelector('svg');
|
||||
return svg && btn.querySelector('[class*="ChevronLeft"]');
|
||||
});
|
||||
|
||||
// Initial date rendering
|
||||
const initialText = screen.getByText(/\w+, \w+ \d+, \d{4}/);
|
||||
const initialDate = initialText.textContent;
|
||||
|
||||
if (prevButton) {
|
||||
fireEvent.click(prevButton);
|
||||
const newText = screen.getByText(/\w+, \w+ \d+, \d{4}/);
|
||||
expect(newText.textContent).not.toBe(initialDate);
|
||||
}
|
||||
});
|
||||
|
||||
it('clicks Today button to reset to current date', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
const todayButton = screen.getByRole('button', { name: /today/i });
|
||||
fireEvent.click(todayButton);
|
||||
// Should display current date
|
||||
expect(screen.getByText(/\w+, \w+ \d+, \d{4}/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Appointments display', () => {
|
||||
it('displays appointments for the selected resource', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
||||
expect(screen.getByText('Jane Smith')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('filters out appointments for other resources', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.queryByText('Bob Johnson')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays appointment customer names', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
||||
expect(screen.getByText('Jane Smith')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays appointment time and duration', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
// Check for time format (e.g., "10:00 AM • 60 min")
|
||||
// Use getAllByText since there might be multiple appointments with same duration
|
||||
const timeElements = screen.getAllByText(/10:00 AM/);
|
||||
expect(timeElements.length).toBeGreaterThan(0);
|
||||
const durationElements = screen.getAllByText(/1h/);
|
||||
expect(durationElements.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Loading states', () => {
|
||||
it('displays loading message when loading', () => {
|
||||
vi.mocked(useAppointments).mockReturnValue({
|
||||
data: [],
|
||||
isLoading: true,
|
||||
} as any);
|
||||
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('scheduler.loadingAppointments')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays empty state when no appointments', () => {
|
||||
vi.mocked(useAppointments).mockReturnValue({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('scheduler.noAppointmentsScheduled')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Week view', () => {
|
||||
it('renders week view when week button is clicked', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
const weekButton = screen.getByRole('button', { name: /^week$/i });
|
||||
fireEvent.click(weekButton);
|
||||
|
||||
// Verify week button is active (has bg-white class)
|
||||
expect(weekButton).toHaveClass('bg-white');
|
||||
});
|
||||
|
||||
it('week view shows different content than day view', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
|
||||
// Get content in day view
|
||||
const dayViewContent = document.body.textContent || '';
|
||||
|
||||
// Switch to week view
|
||||
fireEvent.click(screen.getByRole('button', { name: /^week$/i }));
|
||||
|
||||
// Get content in week view
|
||||
const weekViewContent = document.body.textContent || '';
|
||||
|
||||
// Week view and day view should have different content
|
||||
// (Week view shows multiple days, day view shows single day timeline)
|
||||
expect(weekViewContent).not.toBe(dayViewContent);
|
||||
|
||||
// Week view should show hint text for clicking days
|
||||
expect(screen.getByText(/click a day to view details/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Month view', () => {
|
||||
it('displays calendar grid in month view', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /month/i }));
|
||||
|
||||
// Should show weekday headers
|
||||
expect(screen.getByText('Mon')).toBeInTheDocument();
|
||||
expect(screen.getByText('Tue')).toBeInTheDocument();
|
||||
expect(screen.getByText('Wed')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows appointment count in month view cells', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /month/i }));
|
||||
|
||||
// Should show "2 appts" for the day with 2 appointments
|
||||
expect(screen.getByText(/2 appt/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking a day in month view switches to week view', async () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /month/i }));
|
||||
|
||||
// Find day cells and click one
|
||||
const dayCells = screen.getAllByText(/^\d+$/);
|
||||
if (dayCells.length > 0) {
|
||||
fireEvent.click(dayCells[0].closest('div')!);
|
||||
|
||||
await waitFor(() => {
|
||||
const weekButton = screen.getByRole('button', { name: /week/i });
|
||||
expect(weekButton).toHaveClass('bg-white');
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Drag and drop (day view)', () => {
|
||||
it('displays drag hint in day view', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText(/drag to move/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays click hint in week/month view', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
fireEvent.click(screen.getByRole('button', { name: /week/i }));
|
||||
expect(screen.getByText(/click a day to view details/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Appointment interactions', () => {
|
||||
it('renders appointments with appropriate styling in day view', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
|
||||
// Verify appointments are rendered
|
||||
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
||||
expect(screen.getByText('Jane Smith')).toBeInTheDocument();
|
||||
|
||||
// Verify they have parent elements (appointment containers)
|
||||
const appointment1 = screen.getByText('John Doe').parentElement;
|
||||
const appointment2 = screen.getByText('Jane Smith').parentElement;
|
||||
|
||||
expect(appointment1).toBeInTheDocument();
|
||||
expect(appointment2).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Duration formatting', () => {
|
||||
it('formats duration less than 60 minutes as minutes', () => {
|
||||
const shortAppointment: Appointment = {
|
||||
...mockAppointments[0],
|
||||
durationMinutes: 45,
|
||||
};
|
||||
|
||||
vi.mocked(useAppointments).mockReturnValue({
|
||||
data: [shortAppointment],
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText(/45 min/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('formats duration 60+ minutes as hours', () => {
|
||||
const longAppointment: Appointment = {
|
||||
...mockAppointments[0],
|
||||
durationMinutes: 120,
|
||||
};
|
||||
|
||||
vi.mocked(useAppointments).mockReturnValue({
|
||||
data: [longAppointment],
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText(/2h/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('formats duration with hours and minutes', () => {
|
||||
const mixedAppointment: Appointment = {
|
||||
...mockAppointments[0],
|
||||
durationMinutes: 90,
|
||||
};
|
||||
|
||||
vi.mocked(useAppointments).mockReturnValue({
|
||||
data: [mixedAppointment],
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText(/1h 30m/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accessibility', () => {
|
||||
it('has accessible button labels', () => {
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByRole('button', { name: /^day$/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /^week$/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /^month$/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /^today$/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Overlapping appointments', () => {
|
||||
it('handles overlapping appointments with lane layout', () => {
|
||||
const todayAt10 = new Date();
|
||||
todayAt10.setHours(10, 0, 0, 0);
|
||||
const todayAt1030 = new Date();
|
||||
todayAt1030.setHours(10, 30, 0, 0);
|
||||
|
||||
const overlappingAppointments: Appointment[] = [
|
||||
{
|
||||
...mockAppointments[0],
|
||||
startTime: todayAt10,
|
||||
durationMinutes: 120,
|
||||
},
|
||||
{
|
||||
...mockAppointments[1],
|
||||
id: '2',
|
||||
startTime: todayAt1030,
|
||||
durationMinutes: 60,
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(useAppointments).mockReturnValue({
|
||||
data: overlappingAppointments,
|
||||
isLoading: false,
|
||||
} as any);
|
||||
|
||||
render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('John Doe')).toBeInTheDocument();
|
||||
expect(screen.getByText('Jane Smith')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Props variations', () => {
|
||||
it('works with different resource IDs', () => {
|
||||
render(<ResourceCalendar {...defaultProps} resourceId="resource-2" />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
expect(screen.getByText('Bob Johnson')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('updates when resource name changes', () => {
|
||||
const { rerender } = render(<ResourceCalendar {...defaultProps} />, { wrapper: createWrapper() });
|
||||
expect(screen.getByText('Dr. Smith Calendar')).toBeInTheDocument();
|
||||
|
||||
rerender(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<ResourceCalendar {...defaultProps} resourceName="Dr. Jones" />
|
||||
</QueryClientProvider>
|
||||
);
|
||||
expect(screen.getByText('Dr. Jones Calendar')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
86
frontend/src/components/__tests__/SandboxBanner.test.tsx
Normal file
86
frontend/src/components/__tests__/SandboxBanner.test.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import SandboxBanner from '../SandboxBanner';
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, defaultValue?: string) => defaultValue || key,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('SandboxBanner', () => {
|
||||
const defaultProps = {
|
||||
isSandbox: true,
|
||||
onSwitchToLive: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders when in sandbox mode', () => {
|
||||
render(<SandboxBanner {...defaultProps} />);
|
||||
expect(screen.getByText('TEST MODE')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('returns null when not in sandbox mode', () => {
|
||||
const { container } = render(<SandboxBanner {...defaultProps} isSandbox={false} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('renders banner description', () => {
|
||||
render(<SandboxBanner {...defaultProps} />);
|
||||
expect(screen.getByText(/You are viewing test data/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders switch to live button', () => {
|
||||
render(<SandboxBanner {...defaultProps} />);
|
||||
expect(screen.getByText('Switch to Live')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onSwitchToLive when button clicked', () => {
|
||||
const onSwitchToLive = vi.fn();
|
||||
render(<SandboxBanner {...defaultProps} onSwitchToLive={onSwitchToLive} />);
|
||||
fireEvent.click(screen.getByText('Switch to Live'));
|
||||
expect(onSwitchToLive).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disables button when switching', () => {
|
||||
render(<SandboxBanner {...defaultProps} isSwitching />);
|
||||
expect(screen.getByText('Switching...')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows switching text when isSwitching is true', () => {
|
||||
render(<SandboxBanner {...defaultProps} isSwitching />);
|
||||
expect(screen.getByText('Switching...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders dismiss button when onDismiss provided', () => {
|
||||
render(<SandboxBanner {...defaultProps} onDismiss={() => {}} />);
|
||||
expect(screen.getByTitle('Dismiss')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render dismiss button when onDismiss not provided', () => {
|
||||
render(<SandboxBanner {...defaultProps} />);
|
||||
expect(screen.queryByTitle('Dismiss')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onDismiss when dismiss button clicked', () => {
|
||||
const onDismiss = vi.fn();
|
||||
render(<SandboxBanner {...defaultProps} onDismiss={onDismiss} />);
|
||||
fireEvent.click(screen.getByTitle('Dismiss'));
|
||||
expect(onDismiss).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('has gradient background', () => {
|
||||
const { container } = render(<SandboxBanner {...defaultProps} />);
|
||||
expect(container.firstChild).toHaveClass('bg-gradient-to-r');
|
||||
});
|
||||
|
||||
it('renders flask icon', () => {
|
||||
const { container } = render(<SandboxBanner {...defaultProps} />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
108
frontend/src/components/__tests__/SandboxToggle.test.tsx
Normal file
108
frontend/src/components/__tests__/SandboxToggle.test.tsx
Normal file
@@ -0,0 +1,108 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import SandboxToggle from '../SandboxToggle';
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, defaultValue?: string) => defaultValue || key,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('SandboxToggle', () => {
|
||||
const defaultProps = {
|
||||
isSandbox: false,
|
||||
sandboxEnabled: true,
|
||||
onToggle: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders when sandbox is enabled', () => {
|
||||
render(<SandboxToggle {...defaultProps} />);
|
||||
expect(screen.getByText('Live')).toBeInTheDocument();
|
||||
expect(screen.getByText('Test')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('returns null when sandbox not enabled', () => {
|
||||
const { container } = render(<SandboxToggle {...defaultProps} sandboxEnabled={false} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('highlights Live button when not in sandbox mode', () => {
|
||||
render(<SandboxToggle {...defaultProps} isSandbox={false} />);
|
||||
const liveButton = screen.getByText('Live').closest('button');
|
||||
expect(liveButton).toHaveClass('bg-green-600');
|
||||
});
|
||||
|
||||
it('highlights Test button when in sandbox mode', () => {
|
||||
render(<SandboxToggle {...defaultProps} isSandbox={true} />);
|
||||
const testButton = screen.getByText('Test').closest('button');
|
||||
expect(testButton).toHaveClass('bg-orange-500');
|
||||
});
|
||||
|
||||
it('calls onToggle with false when Live clicked', () => {
|
||||
const onToggle = vi.fn();
|
||||
render(<SandboxToggle {...defaultProps} isSandbox={true} onToggle={onToggle} />);
|
||||
fireEvent.click(screen.getByText('Live'));
|
||||
expect(onToggle).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('calls onToggle with true when Test clicked', () => {
|
||||
const onToggle = vi.fn();
|
||||
render(<SandboxToggle {...defaultProps} isSandbox={false} onToggle={onToggle} />);
|
||||
fireEvent.click(screen.getByText('Test'));
|
||||
expect(onToggle).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('disables Live button when already in live mode', () => {
|
||||
render(<SandboxToggle {...defaultProps} isSandbox={false} />);
|
||||
const liveButton = screen.getByText('Live').closest('button');
|
||||
expect(liveButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables Test button when already in sandbox mode', () => {
|
||||
render(<SandboxToggle {...defaultProps} isSandbox={true} />);
|
||||
const testButton = screen.getByText('Test').closest('button');
|
||||
expect(testButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables both buttons when toggling', () => {
|
||||
render(<SandboxToggle {...defaultProps} isToggling />);
|
||||
const liveButton = screen.getByText('Live').closest('button');
|
||||
const testButton = screen.getByText('Test').closest('button');
|
||||
expect(liveButton).toBeDisabled();
|
||||
expect(testButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('applies opacity when toggling', () => {
|
||||
render(<SandboxToggle {...defaultProps} isToggling />);
|
||||
const liveButton = screen.getByText('Live').closest('button');
|
||||
expect(liveButton).toHaveClass('opacity-50');
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<SandboxToggle {...defaultProps} className="custom-class" />);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('has title for Live button', () => {
|
||||
render(<SandboxToggle {...defaultProps} />);
|
||||
const liveButton = screen.getByText('Live').closest('button');
|
||||
expect(liveButton).toHaveAttribute('title', 'Live Mode - Production data');
|
||||
});
|
||||
|
||||
it('has title for Test button', () => {
|
||||
render(<SandboxToggle {...defaultProps} />);
|
||||
const testButton = screen.getByText('Test').closest('button');
|
||||
expect(testButton).toHaveAttribute('title', 'Test Mode - Sandbox data');
|
||||
});
|
||||
|
||||
it('renders icons', () => {
|
||||
const { container } = render(<SandboxToggle {...defaultProps} />);
|
||||
const svgs = container.querySelectorAll('svg');
|
||||
expect(svgs.length).toBe(2); // Zap and FlaskConical icons
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render } from '@testing-library/react';
|
||||
import SmoothScheduleLogo from '../SmoothScheduleLogo';
|
||||
|
||||
describe('SmoothScheduleLogo', () => {
|
||||
it('renders an SVG element', () => {
|
||||
const { container } = render(<SmoothScheduleLogo />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('has correct viewBox', () => {
|
||||
const { container } = render(<SmoothScheduleLogo />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toHaveAttribute('viewBox', '0 0 1730 1100');
|
||||
});
|
||||
|
||||
it('uses currentColor for fill', () => {
|
||||
const { container } = render(<SmoothScheduleLogo />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toHaveAttribute('fill', 'currentColor');
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<SmoothScheduleLogo className="custom-logo-class" />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toHaveClass('custom-logo-class');
|
||||
});
|
||||
|
||||
it('renders without className when not provided', () => {
|
||||
const { container } = render(<SmoothScheduleLogo />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('contains path elements', () => {
|
||||
const { container } = render(<SmoothScheduleLogo />);
|
||||
const paths = container.querySelectorAll('path');
|
||||
expect(paths.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('has xmlns attribute', () => {
|
||||
const { container } = render(<SmoothScheduleLogo />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toHaveAttribute('xmlns', 'http://www.w3.org/2000/svg');
|
||||
});
|
||||
});
|
||||
716
frontend/src/components/__tests__/TopBar.test.tsx
Normal file
716
frontend/src/components/__tests__/TopBar.test.tsx
Normal file
@@ -0,0 +1,716 @@
|
||||
/**
|
||||
* Unit tests for TopBar component
|
||||
*
|
||||
* Tests the top navigation bar that appears at the top of the application.
|
||||
* Covers:
|
||||
* - Rendering of all UI elements (search, theme toggle, notifications, etc.)
|
||||
* - Menu button for mobile view
|
||||
* - Theme toggle functionality
|
||||
* - User profile dropdown integration
|
||||
* - Language selector integration
|
||||
* - Notification dropdown integration
|
||||
* - Sandbox toggle integration
|
||||
* - Search input
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import TopBar from '../TopBar';
|
||||
import { User } from '../../types';
|
||||
|
||||
// Mock child components
|
||||
vi.mock('../UserProfileDropdown', () => ({
|
||||
default: ({ user }: { user: User }) => (
|
||||
<div data-testid="user-profile-dropdown">User: {user.email}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('../LanguageSelector', () => ({
|
||||
default: () => <div data-testid="language-selector">Language Selector</div>,
|
||||
}));
|
||||
|
||||
vi.mock('../NotificationDropdown', () => ({
|
||||
default: ({ onTicketClick }: { onTicketClick?: (id: string) => void }) => (
|
||||
<div data-testid="notification-dropdown">Notifications</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('../SandboxToggle', () => ({
|
||||
default: ({ isSandbox, sandboxEnabled, onToggle, isToggling }: any) => (
|
||||
<div data-testid="sandbox-toggle">
|
||||
Sandbox: {isSandbox ? 'On' : 'Off'}
|
||||
<button onClick={onToggle} disabled={isToggling}>
|
||||
Toggle Sandbox
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock SandboxContext
|
||||
const mockUseSandbox = vi.fn();
|
||||
vi.mock('../../contexts/SandboxContext', () => ({
|
||||
useSandbox: () => mockUseSandbox(),
|
||||
}));
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => {
|
||||
const translations: Record<string, string> = {
|
||||
'common.search': 'Search...',
|
||||
};
|
||||
return translations[key] || key;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Test data factory for User objects
|
||||
const createMockUser = (overrides?: Partial<User>): User => ({
|
||||
id: '1',
|
||||
email: 'test@example.com',
|
||||
firstName: 'Test',
|
||||
lastName: 'User',
|
||||
role: 'owner',
|
||||
phone: '+1234567890',
|
||||
preferences: {
|
||||
email: true,
|
||||
sms: false,
|
||||
in_app: true,
|
||||
},
|
||||
twoFactorEnabled: false,
|
||||
profilePictureUrl: undefined,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
// Wrapper component that provides router context
|
||||
const renderWithRouter = (ui: React.ReactElement) => {
|
||||
return render(<BrowserRouter>{ui}</BrowserRouter>);
|
||||
};
|
||||
|
||||
describe('TopBar', () => {
|
||||
const mockToggleTheme = vi.fn();
|
||||
const mockOnMenuClick = vi.fn();
|
||||
const mockOnTicketClick = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockUseSandbox.mockReturnValue({
|
||||
isSandbox: false,
|
||||
sandboxEnabled: true,
|
||||
toggleSandbox: vi.fn(),
|
||||
isToggling: false,
|
||||
});
|
||||
});
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('should render the top bar with all main elements', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('user-profile-dropdown')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('language-selector')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('notification-dropdown')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('sandbox-toggle')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render search input on desktop', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search...');
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
expect(searchInput).toHaveClass('w-full');
|
||||
});
|
||||
|
||||
it('should render mobile menu button', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const menuButton = screen.getByLabelText('Open sidebar');
|
||||
expect(menuButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should pass user to UserProfileDropdown', () => {
|
||||
const user = createMockUser({ email: 'john@example.com' });
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('User: john@example.com')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render with dark mode styles when isDarkMode is true', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
const { container } = renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={true}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const header = container.querySelector('header');
|
||||
expect(header).toHaveClass('dark:bg-gray-800', 'dark:border-gray-700');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Theme Toggle', () => {
|
||||
it('should render moon icon when in light mode', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
// The button should exist
|
||||
const buttons = screen.getAllByRole('button');
|
||||
const themeButton = buttons.find(btn =>
|
||||
btn.className.includes('text-gray-400')
|
||||
);
|
||||
expect(themeButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render sun icon when in dark mode', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={true}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
// The button should exist
|
||||
const buttons = screen.getAllByRole('button');
|
||||
const themeButton = buttons.find(btn =>
|
||||
btn.className.includes('text-gray-400')
|
||||
);
|
||||
expect(themeButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call toggleTheme when theme button is clicked', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
// Find the theme toggle button by finding buttons, then clicking the one with the theme classes
|
||||
const buttons = screen.getAllByRole('button');
|
||||
// The theme button is the one with the hover styles and not the menu button
|
||||
const themeButton = buttons.find(btn =>
|
||||
btn.className.includes('text-gray-400') &&
|
||||
btn.className.includes('hover:text-gray-600') &&
|
||||
!btn.getAttribute('aria-label')
|
||||
);
|
||||
|
||||
expect(themeButton).toBeTruthy();
|
||||
if (themeButton) {
|
||||
fireEvent.click(themeButton);
|
||||
expect(mockToggleTheme).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Mobile Menu Button', () => {
|
||||
it('should render menu button with correct aria-label', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const menuButton = screen.getByLabelText('Open sidebar');
|
||||
expect(menuButton).toHaveAttribute('aria-label', 'Open sidebar');
|
||||
});
|
||||
|
||||
it('should call onMenuClick when menu button is clicked', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const menuButton = screen.getByLabelText('Open sidebar');
|
||||
fireEvent.click(menuButton);
|
||||
|
||||
expect(mockOnMenuClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should have mobile-only classes on menu button', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
const { container } = renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const menuButton = screen.getByLabelText('Open sidebar');
|
||||
expect(menuButton).toHaveClass('md:hidden');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Search Input', () => {
|
||||
it('should render search input with correct placeholder', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search...');
|
||||
expect(searchInput).toHaveAttribute('type', 'text');
|
||||
});
|
||||
|
||||
it('should have search icon', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
// Search icon should be present
|
||||
const searchInput = screen.getByPlaceholderText('Search...');
|
||||
expect(searchInput.parentElement?.querySelector('span')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should allow typing in search input', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search...') as HTMLInputElement;
|
||||
fireEvent.change(searchInput, { target: { value: 'test query' } });
|
||||
|
||||
expect(searchInput.value).toBe('test query');
|
||||
});
|
||||
|
||||
it('should have focus styles on search input', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search...');
|
||||
expect(searchInput).toHaveClass('focus:outline-none', 'focus:border-brand-500');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Sandbox Integration', () => {
|
||||
it('should render SandboxToggle component', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('sandbox-toggle')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should pass sandbox state to SandboxToggle', () => {
|
||||
const user = createMockUser();
|
||||
mockUseSandbox.mockReturnValue({
|
||||
isSandbox: true,
|
||||
sandboxEnabled: true,
|
||||
toggleSandbox: vi.fn(),
|
||||
isToggling: false,
|
||||
});
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/Sandbox: On/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle sandbox toggle being disabled', () => {
|
||||
const user = createMockUser();
|
||||
mockUseSandbox.mockReturnValue({
|
||||
isSandbox: false,
|
||||
sandboxEnabled: false,
|
||||
toggleSandbox: vi.fn(),
|
||||
isToggling: false,
|
||||
});
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('sandbox-toggle')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Notification Integration', () => {
|
||||
it('should render NotificationDropdown', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('notification-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should pass onTicketClick to NotificationDropdown when provided', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
onTicketClick={mockOnTicketClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('notification-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should work without onTicketClick prop', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('notification-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Language Selector Integration', () => {
|
||||
it('should render LanguageSelector', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('language-selector')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Different User Roles', () => {
|
||||
it('should render for owner role', () => {
|
||||
const user = createMockUser({ role: 'owner' });
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('user-profile-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render for manager role', () => {
|
||||
const user = createMockUser({ role: 'manager' });
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('user-profile-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render for staff role', () => {
|
||||
const user = createMockUser({ role: 'staff' });
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('user-profile-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render for platform roles', () => {
|
||||
const user = createMockUser({ role: 'platform_manager' });
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('user-profile-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Layout and Styling', () => {
|
||||
it('should have fixed height', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
const { container } = renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const header = container.querySelector('header');
|
||||
expect(header).toHaveClass('h-16');
|
||||
});
|
||||
|
||||
it('should have border at bottom', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
const { container } = renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const header = container.querySelector('header');
|
||||
expect(header).toHaveClass('border-b');
|
||||
});
|
||||
|
||||
it('should use flexbox layout', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
const { container } = renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const header = container.querySelector('header');
|
||||
expect(header).toHaveClass('flex', 'items-center', 'justify-between');
|
||||
});
|
||||
|
||||
it('should have responsive padding', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
const { container } = renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const header = container.querySelector('header');
|
||||
expect(header).toHaveClass('px-4', 'sm:px-8');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accessibility', () => {
|
||||
it('should have semantic header element', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
const { container } = renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(container.querySelector('header')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should have proper button roles', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const buttons = screen.getAllByRole('button');
|
||||
expect(buttons.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should have focus styles on interactive elements', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const menuButton = screen.getByLabelText('Open sidebar');
|
||||
expect(menuButton).toHaveClass('focus:outline-none', 'focus:ring-2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Responsive Behavior', () => {
|
||||
it('should hide search on mobile', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
const { container } = renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
// Search container is a relative div with hidden md:block classes
|
||||
const searchContainer = container.querySelector('.hidden.md\\:block');
|
||||
expect(searchContainer).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show menu button only on mobile', () => {
|
||||
const user = createMockUser();
|
||||
|
||||
renderWithRouter(
|
||||
<TopBar
|
||||
user={user}
|
||||
isDarkMode={false}
|
||||
toggleTheme={mockToggleTheme}
|
||||
onMenuClick={mockOnMenuClick}
|
||||
/>
|
||||
);
|
||||
|
||||
const menuButton = screen.getByLabelText('Open sidebar');
|
||||
expect(menuButton).toHaveClass('md:hidden');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -508,4 +508,230 @@ describe('TrialBanner', () => {
|
||||
expect(screen.getByText(/trial active/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Additional Edge Cases', () => {
|
||||
it('should handle negative days left gracefully', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: -5,
|
||||
});
|
||||
|
||||
renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
// Should still render (backend shouldn't send this, but defensive coding)
|
||||
expect(screen.getByText(/-5 days left in trial/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle fractional days by rounding', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 5.7 as number,
|
||||
});
|
||||
|
||||
renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
// Should display with the value received
|
||||
expect(screen.getByText(/5.7 days left in trial/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should transition from urgent to non-urgent styling on update', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 3,
|
||||
});
|
||||
|
||||
const { container, rerender } = renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
// Initially urgent
|
||||
expect(container.querySelector('.from-red-500')).toBeInTheDocument();
|
||||
|
||||
// Update to non-urgent
|
||||
const updatedBusiness = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 10,
|
||||
});
|
||||
|
||||
rerender(
|
||||
<BrowserRouter>
|
||||
<TrialBanner business={updatedBusiness} />
|
||||
</BrowserRouter>
|
||||
);
|
||||
|
||||
// Should now be non-urgent
|
||||
expect(container.querySelector('.from-blue-600')).toBeInTheDocument();
|
||||
expect(container.querySelector('.from-red-500')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle business without name gracefully', () => {
|
||||
const business = createMockBusiness({
|
||||
name: '',
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 10,
|
||||
});
|
||||
|
||||
renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
// Should still render the banner
|
||||
expect(screen.getByText(/trial active/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle switching from active to inactive trial', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 5,
|
||||
});
|
||||
|
||||
const { rerender } = renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
expect(screen.getByText(/trial active/i)).toBeInTheDocument();
|
||||
|
||||
// Update to inactive
|
||||
const updatedBusiness = createMockBusiness({
|
||||
isTrialActive: false,
|
||||
daysLeftInTrial: 5,
|
||||
});
|
||||
|
||||
rerender(
|
||||
<BrowserRouter>
|
||||
<TrialBanner business={updatedBusiness} />
|
||||
</BrowserRouter>
|
||||
);
|
||||
|
||||
// Should no longer render
|
||||
expect(screen.queryByText(/trial active/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Button Interactions', () => {
|
||||
it('should prevent multiple rapid clicks on upgrade button', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 10,
|
||||
});
|
||||
|
||||
renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
const upgradeButton = screen.getByRole('button', { name: /upgrade now/i });
|
||||
|
||||
// Rapid clicks
|
||||
fireEvent.click(upgradeButton);
|
||||
fireEvent.click(upgradeButton);
|
||||
fireEvent.click(upgradeButton);
|
||||
|
||||
// Navigate should still only be called once per click (no debouncing in component)
|
||||
expect(mockNavigate).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('should not interfere with other buttons after dismiss', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 10,
|
||||
});
|
||||
|
||||
renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
const dismissButton = screen.getByRole('button', { name: /dismiss/i });
|
||||
fireEvent.click(dismissButton);
|
||||
|
||||
// Banner is gone
|
||||
expect(screen.queryByText(/trial active/i)).not.toBeInTheDocument();
|
||||
|
||||
// Upgrade button should also be gone
|
||||
expect(screen.queryByRole('button', { name: /upgrade now/i })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Visual States', () => {
|
||||
it('should have shadow and proper background for visibility', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 10,
|
||||
});
|
||||
|
||||
const { container } = renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
const banner = container.querySelector('.shadow-md');
|
||||
expect(banner).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should have gradient background for visual appeal', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 10,
|
||||
});
|
||||
|
||||
const { container } = renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
const gradient = container.querySelector('.bg-gradient-to-r');
|
||||
expect(gradient).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show hover states on interactive elements', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 10,
|
||||
});
|
||||
|
||||
renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
const upgradeButton = screen.getByRole('button', { name: /upgrade now/i });
|
||||
expect(upgradeButton).toHaveClass('hover:bg-blue-50');
|
||||
});
|
||||
|
||||
it('should have appropriate spacing and padding', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 10,
|
||||
});
|
||||
|
||||
const { container } = renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
// Check for padding classes
|
||||
const contentContainer = container.querySelector('.py-3');
|
||||
expect(contentContainer).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Icon Rendering', () => {
|
||||
it('should render icons with proper size', () => {
|
||||
const business = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 10,
|
||||
});
|
||||
|
||||
const { container } = renderWithRouter(<TrialBanner business={business} />);
|
||||
|
||||
// Icons should have consistent size classes
|
||||
const iconContainer = container.querySelector('.rounded-full');
|
||||
expect(iconContainer).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show different icons for urgent vs non-urgent states', () => {
|
||||
const nonUrgentBusiness = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 10,
|
||||
});
|
||||
|
||||
const { container: container1, unmount } = renderWithRouter(
|
||||
<TrialBanner business={nonUrgentBusiness} />
|
||||
);
|
||||
|
||||
// Non-urgent should not have pulse animation
|
||||
expect(container1.querySelector('.animate-pulse')).not.toBeInTheDocument();
|
||||
|
||||
unmount();
|
||||
|
||||
const urgentBusiness = createMockBusiness({
|
||||
isTrialActive: true,
|
||||
daysLeftInTrial: 2,
|
||||
});
|
||||
|
||||
const { container: container2 } = renderWithRouter(
|
||||
<TrialBanner business={urgentBusiness} />
|
||||
);
|
||||
|
||||
// Urgent should have pulse animation
|
||||
expect(container2.querySelector('.animate-pulse')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
567
frontend/src/components/__tests__/UpgradePrompt.test.tsx
Normal file
567
frontend/src/components/__tests__/UpgradePrompt.test.tsx
Normal file
@@ -0,0 +1,567 @@
|
||||
/**
|
||||
* Unit tests for UpgradePrompt, LockedSection, and LockedButton components
|
||||
*
|
||||
* Tests upgrade prompts that appear when features are not available in the current plan.
|
||||
* Covers:
|
||||
* - Different variants (inline, banner, overlay)
|
||||
* - Different sizes (sm, md, lg)
|
||||
* - Feature names and descriptions
|
||||
* - Navigation to billing page
|
||||
* - LockedSection wrapper behavior
|
||||
* - LockedButton disabled state and tooltip
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, within } from '@testing-library/react';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import {
|
||||
UpgradePrompt,
|
||||
LockedSection,
|
||||
LockedButton,
|
||||
} from '../UpgradePrompt';
|
||||
import { FeatureKey } from '../../hooks/usePlanFeatures';
|
||||
|
||||
// Mock react-router-dom's Link component
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual('react-router-dom');
|
||||
return {
|
||||
...actual,
|
||||
Link: ({ to, children, className, ...props }: any) => (
|
||||
<a href={to} className={className} {...props}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
// Wrapper component that provides router context
|
||||
const renderWithRouter = (ui: React.ReactElement) => {
|
||||
return render(<BrowserRouter>{ui}</BrowserRouter>);
|
||||
};
|
||||
|
||||
describe('UpgradePrompt', () => {
|
||||
describe('Inline Variant', () => {
|
||||
it('should render inline upgrade prompt with lock icon', () => {
|
||||
renderWithRouter(<UpgradePrompt feature="sms_reminders" variant="inline" />);
|
||||
|
||||
expect(screen.getByText('Upgrade Required')).toBeInTheDocument();
|
||||
// Check for styling classes
|
||||
const container = screen.getByText('Upgrade Required').parentElement;
|
||||
expect(container).toHaveClass('bg-amber-50', 'text-amber-700');
|
||||
});
|
||||
|
||||
it('should render small badge style for inline variant', () => {
|
||||
const { container } = renderWithRouter(
|
||||
<UpgradePrompt feature="webhooks" variant="inline" />
|
||||
);
|
||||
|
||||
const badge = container.querySelector('.bg-amber-50');
|
||||
expect(badge).toBeInTheDocument();
|
||||
expect(badge).toHaveClass('text-xs', 'rounded-md');
|
||||
});
|
||||
|
||||
it('should not show description or upgrade button in inline variant', () => {
|
||||
renderWithRouter(<UpgradePrompt feature="api_access" variant="inline" />);
|
||||
|
||||
expect(screen.queryByText(/integrate with external/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('link', { name: /upgrade your plan/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render for any feature in inline mode', () => {
|
||||
const features: FeatureKey[] = ['plugins', 'custom_domain', 'white_label'];
|
||||
|
||||
features.forEach((feature) => {
|
||||
const { unmount } = renderWithRouter(
|
||||
<UpgradePrompt feature={feature} variant="inline" />
|
||||
);
|
||||
expect(screen.getByText('Upgrade Required')).toBeInTheDocument();
|
||||
unmount();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Banner Variant', () => {
|
||||
it('should render banner with feature name and crown icon', () => {
|
||||
renderWithRouter(<UpgradePrompt feature="sms_reminders" variant="banner" />);
|
||||
|
||||
expect(screen.getByText(/sms reminders.*upgrade required/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render feature description by default', () => {
|
||||
renderWithRouter(<UpgradePrompt feature="sms_reminders" variant="banner" />);
|
||||
|
||||
expect(
|
||||
screen.getByText(/send automated sms reminders to customers and staff/i)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should hide description when showDescription is false', () => {
|
||||
renderWithRouter(
|
||||
<UpgradePrompt
|
||||
feature="sms_reminders"
|
||||
variant="banner"
|
||||
showDescription={false}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.queryByText(/send automated sms reminders/i)
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render upgrade button linking to billing settings', () => {
|
||||
renderWithRouter(<UpgradePrompt feature="webhooks" variant="banner" />);
|
||||
|
||||
const upgradeLink = screen.getByRole('link', { name: /upgrade your plan/i });
|
||||
expect(upgradeLink).toBeInTheDocument();
|
||||
expect(upgradeLink).toHaveAttribute('href', '/settings/billing');
|
||||
});
|
||||
|
||||
it('should have gradient styling for banner variant', () => {
|
||||
const { container } = renderWithRouter(
|
||||
<UpgradePrompt feature="api_access" variant="banner" />
|
||||
);
|
||||
|
||||
const banner = container.querySelector('.bg-gradient-to-br.from-amber-50');
|
||||
expect(banner).toBeInTheDocument();
|
||||
expect(banner).toHaveClass('border-2', 'border-amber-300');
|
||||
});
|
||||
|
||||
it('should render crown icon in banner', () => {
|
||||
renderWithRouter(<UpgradePrompt feature="custom_domain" variant="banner" />);
|
||||
|
||||
// Crown icon should be in the button text
|
||||
const upgradeButton = screen.getByRole('link', { name: /upgrade your plan/i });
|
||||
expect(upgradeButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render all feature names correctly', () => {
|
||||
const features: FeatureKey[] = [
|
||||
'webhooks',
|
||||
'api_access',
|
||||
'custom_domain',
|
||||
'white_label',
|
||||
'plugins',
|
||||
];
|
||||
|
||||
features.forEach((feature) => {
|
||||
const { unmount } = renderWithRouter(
|
||||
<UpgradePrompt feature={feature} variant="banner" />
|
||||
);
|
||||
// Feature name should be in the heading
|
||||
expect(screen.getByRole('heading', { level: 3 })).toBeInTheDocument();
|
||||
unmount();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Overlay Variant', () => {
|
||||
it('should render overlay with blurred children', () => {
|
||||
renderWithRouter(
|
||||
<UpgradePrompt feature="sms_reminders" variant="overlay">
|
||||
<div data-testid="locked-content">Locked Content</div>
|
||||
</UpgradePrompt>
|
||||
);
|
||||
|
||||
const lockedContent = screen.getByTestId('locked-content');
|
||||
expect(lockedContent).toBeInTheDocument();
|
||||
|
||||
// Check that parent has blur styling
|
||||
const parent = lockedContent.parentElement;
|
||||
expect(parent).toHaveClass('blur-sm', 'opacity-50');
|
||||
});
|
||||
|
||||
it('should render feature name and description in overlay', () => {
|
||||
renderWithRouter(
|
||||
<UpgradePrompt feature="webhooks" variant="overlay">
|
||||
<div>Content</div>
|
||||
</UpgradePrompt>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Webhooks')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/integrate with external services using webhooks/i)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render lock icon in overlay', () => {
|
||||
const { container } = renderWithRouter(
|
||||
<UpgradePrompt feature="api_access" variant="overlay">
|
||||
<div>Content</div>
|
||||
</UpgradePrompt>
|
||||
);
|
||||
|
||||
// Lock icon should be in a rounded circle
|
||||
const iconCircle = container.querySelector('.rounded-full.bg-gradient-to-br');
|
||||
expect(iconCircle).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render upgrade button in overlay', () => {
|
||||
renderWithRouter(
|
||||
<UpgradePrompt feature="custom_domain" variant="overlay">
|
||||
<div>Content</div>
|
||||
</UpgradePrompt>
|
||||
);
|
||||
|
||||
const upgradeLink = screen.getByRole('link', { name: /upgrade your plan/i });
|
||||
expect(upgradeLink).toBeInTheDocument();
|
||||
expect(upgradeLink).toHaveAttribute('href', '/settings/billing');
|
||||
});
|
||||
|
||||
it('should apply small size styling', () => {
|
||||
const { container } = renderWithRouter(
|
||||
<UpgradePrompt feature="plugins" variant="overlay" size="sm">
|
||||
<div>Content</div>
|
||||
</UpgradePrompt>
|
||||
);
|
||||
|
||||
const overlayContent = container.querySelector('.p-4');
|
||||
expect(overlayContent).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should apply medium size styling by default', () => {
|
||||
const { container } = renderWithRouter(
|
||||
<UpgradePrompt feature="plugins" variant="overlay">
|
||||
<div>Content</div>
|
||||
</UpgradePrompt>
|
||||
);
|
||||
|
||||
const overlayContent = container.querySelector('.p-6');
|
||||
expect(overlayContent).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should apply large size styling', () => {
|
||||
const { container } = renderWithRouter(
|
||||
<UpgradePrompt feature="plugins" variant="overlay" size="lg">
|
||||
<div>Content</div>
|
||||
</UpgradePrompt>
|
||||
);
|
||||
|
||||
const overlayContent = container.querySelector('.p-8');
|
||||
expect(overlayContent).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should make children non-interactive', () => {
|
||||
renderWithRouter(
|
||||
<UpgradePrompt feature="white_label" variant="overlay">
|
||||
<button data-testid="locked-button">Click Me</button>
|
||||
</UpgradePrompt>
|
||||
);
|
||||
|
||||
const button = screen.getByTestId('locked-button');
|
||||
const parent = button.parentElement;
|
||||
expect(parent).toHaveClass('pointer-events-none');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Default Behavior', () => {
|
||||
it('should default to banner variant when no variant specified', () => {
|
||||
renderWithRouter(<UpgradePrompt feature="sms_reminders" />);
|
||||
|
||||
// Banner should show feature name in heading
|
||||
expect(screen.getByRole('heading', { level: 3 })).toBeInTheDocument();
|
||||
expect(screen.getByText(/sms reminders.*upgrade required/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show description by default', () => {
|
||||
renderWithRouter(<UpgradePrompt feature="webhooks" />);
|
||||
|
||||
expect(
|
||||
screen.getByText(/integrate with external services/i)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should use medium size by default', () => {
|
||||
const { container } = renderWithRouter(
|
||||
<UpgradePrompt feature="plugins" variant="overlay">
|
||||
<div>Content</div>
|
||||
</UpgradePrompt>
|
||||
);
|
||||
|
||||
const overlayContent = container.querySelector('.p-6');
|
||||
expect(overlayContent).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('LockedSection', () => {
|
||||
describe('Unlocked State', () => {
|
||||
it('should render children when not locked', () => {
|
||||
renderWithRouter(
|
||||
<LockedSection feature="sms_reminders" isLocked={false}>
|
||||
<div data-testid="content">Available Content</div>
|
||||
</LockedSection>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('content')).toBeInTheDocument();
|
||||
expect(screen.getByText('Available Content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should not show upgrade prompt when unlocked', () => {
|
||||
renderWithRouter(
|
||||
<LockedSection feature="webhooks" isLocked={false}>
|
||||
<div>Content</div>
|
||||
</LockedSection>
|
||||
);
|
||||
|
||||
expect(screen.queryByText(/upgrade required/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('link', { name: /upgrade your plan/i })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Locked State', () => {
|
||||
it('should show banner prompt by default when locked', () => {
|
||||
renderWithRouter(
|
||||
<LockedSection feature="sms_reminders" isLocked={true}>
|
||||
<div>Content</div>
|
||||
</LockedSection>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/sms reminders.*upgrade required/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show overlay prompt when variant is overlay', () => {
|
||||
renderWithRouter(
|
||||
<LockedSection feature="api_access" isLocked={true} variant="overlay">
|
||||
<div data-testid="locked-content">Locked Content</div>
|
||||
</LockedSection>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('locked-content')).toBeInTheDocument();
|
||||
expect(screen.getByText('API Access')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show fallback content instead of upgrade prompt when provided', () => {
|
||||
renderWithRouter(
|
||||
<LockedSection
|
||||
feature="custom_domain"
|
||||
isLocked={true}
|
||||
fallback={<div data-testid="fallback">Custom Fallback</div>}
|
||||
>
|
||||
<div>Original Content</div>
|
||||
</LockedSection>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('fallback')).toBeInTheDocument();
|
||||
expect(screen.getByText('Custom Fallback')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/upgrade required/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should not render original children when locked without overlay', () => {
|
||||
renderWithRouter(
|
||||
<LockedSection feature="webhooks" isLocked={true} variant="banner">
|
||||
<div data-testid="original">Original Content</div>
|
||||
</LockedSection>
|
||||
);
|
||||
|
||||
expect(screen.queryByTestId('original')).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/webhooks.*upgrade required/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render blurred children with overlay variant', () => {
|
||||
renderWithRouter(
|
||||
<LockedSection feature="plugins" isLocked={true} variant="overlay">
|
||||
<div data-testid="blurred-content">Blurred Content</div>
|
||||
</LockedSection>
|
||||
);
|
||||
|
||||
const content = screen.getByTestId('blurred-content');
|
||||
expect(content).toBeInTheDocument();
|
||||
expect(content.parentElement).toHaveClass('blur-sm');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Different Features', () => {
|
||||
it('should work with different feature keys', () => {
|
||||
const features: FeatureKey[] = [
|
||||
'white_label',
|
||||
'custom_oauth',
|
||||
'can_create_plugins',
|
||||
'tasks',
|
||||
];
|
||||
|
||||
features.forEach((feature) => {
|
||||
const { unmount } = renderWithRouter(
|
||||
<LockedSection feature={feature} isLocked={true}>
|
||||
<div>Content</div>
|
||||
</LockedSection>
|
||||
);
|
||||
expect(screen.getByRole('heading', { level: 3 })).toBeInTheDocument();
|
||||
unmount();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('LockedButton', () => {
|
||||
describe('Unlocked State', () => {
|
||||
it('should render normal clickable button when not locked', () => {
|
||||
const handleClick = vi.fn();
|
||||
renderWithRouter(
|
||||
<LockedButton
|
||||
feature="sms_reminders"
|
||||
isLocked={false}
|
||||
onClick={handleClick}
|
||||
className="custom-class"
|
||||
>
|
||||
Click Me
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: /click me/i });
|
||||
expect(button).toBeInTheDocument();
|
||||
expect(button).not.toBeDisabled();
|
||||
expect(button).toHaveClass('custom-class');
|
||||
|
||||
fireEvent.click(button);
|
||||
expect(handleClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should not show lock icon when unlocked', () => {
|
||||
renderWithRouter(
|
||||
<LockedButton feature="webhooks" isLocked={false}>
|
||||
Submit
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: /submit/i });
|
||||
expect(button.querySelector('svg')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Locked State', () => {
|
||||
it('should render disabled button with lock icon when locked', () => {
|
||||
renderWithRouter(
|
||||
<LockedButton feature="api_access" isLocked={true}>
|
||||
Submit
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button', { name: /submit/i });
|
||||
expect(button).toBeDisabled();
|
||||
expect(button).toHaveClass('opacity-50', 'cursor-not-allowed');
|
||||
});
|
||||
|
||||
it('should display lock icon when locked', () => {
|
||||
renderWithRouter(
|
||||
<LockedButton feature="custom_domain" isLocked={true}>
|
||||
Save
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button.textContent).toContain('Save');
|
||||
});
|
||||
|
||||
it('should show tooltip on hover when locked', () => {
|
||||
const { container } = renderWithRouter(
|
||||
<LockedButton feature="plugins" isLocked={true}>
|
||||
Create Plugin
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
// Tooltip should exist in DOM
|
||||
const tooltip = container.querySelector('.opacity-0');
|
||||
expect(tooltip).toBeInTheDocument();
|
||||
expect(tooltip?.textContent).toContain('Upgrade Required');
|
||||
});
|
||||
|
||||
it('should not trigger onClick when locked', () => {
|
||||
const handleClick = vi.fn();
|
||||
renderWithRouter(
|
||||
<LockedButton
|
||||
feature="white_label"
|
||||
isLocked={true}
|
||||
onClick={handleClick}
|
||||
>
|
||||
Click Me
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
expect(handleClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should apply custom className even when locked', () => {
|
||||
renderWithRouter(
|
||||
<LockedButton
|
||||
feature="webhooks"
|
||||
isLocked={true}
|
||||
className="custom-btn"
|
||||
>
|
||||
Submit
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toHaveClass('custom-btn');
|
||||
});
|
||||
|
||||
it('should display feature name in tooltip', () => {
|
||||
const { container } = renderWithRouter(
|
||||
<LockedButton feature="sms_reminders" isLocked={true}>
|
||||
Send SMS
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
const tooltip = container.querySelector('.whitespace-nowrap');
|
||||
expect(tooltip?.textContent).toContain('SMS Reminders');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Different Features', () => {
|
||||
it('should work with various feature keys', () => {
|
||||
const features: FeatureKey[] = [
|
||||
'export_data',
|
||||
'video_conferencing',
|
||||
'two_factor_auth',
|
||||
'masked_calling',
|
||||
];
|
||||
|
||||
features.forEach((feature) => {
|
||||
const { unmount } = renderWithRouter(
|
||||
<LockedButton feature={feature} isLocked={true}>
|
||||
Action
|
||||
</LockedButton>
|
||||
);
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toBeDisabled();
|
||||
unmount();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accessibility', () => {
|
||||
it('should have proper button role when unlocked', () => {
|
||||
renderWithRouter(
|
||||
<LockedButton feature="plugins" isLocked={false}>
|
||||
Save
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should have proper button role when locked', () => {
|
||||
renderWithRouter(
|
||||
<LockedButton feature="webhooks" isLocked={true}>
|
||||
Submit
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: /submit/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should indicate disabled state for screen readers', () => {
|
||||
renderWithRouter(
|
||||
<LockedButton feature="api_access" isLocked={true}>
|
||||
Create
|
||||
</LockedButton>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toHaveAttribute('disabled');
|
||||
});
|
||||
});
|
||||
});
|
||||
242
frontend/src/components/marketing/DynamicPricingCards.tsx
Normal file
242
frontend/src/components/marketing/DynamicPricingCards.tsx
Normal file
@@ -0,0 +1,242 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Check, Loader2 } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
usePublicPlans,
|
||||
formatPrice,
|
||||
PublicPlanVersion,
|
||||
} from '../../hooks/usePublicPlans';
|
||||
|
||||
interface DynamicPricingCardsProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const DynamicPricingCards: React.FC<DynamicPricingCardsProps> = ({ className = '' }) => {
|
||||
const { t } = useTranslation();
|
||||
const { data: plans, isLoading, error } = usePublicPlans();
|
||||
const [billingPeriod, setBillingPeriod] = useState<'monthly' | 'annual'>('monthly');
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-brand-600" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !plans) {
|
||||
return (
|
||||
<div className="text-center py-20 text-gray-500 dark:text-gray-400">
|
||||
{t('marketing.pricing.loadError', 'Unable to load pricing. Please try again later.')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Sort plans by display_order
|
||||
const sortedPlans = [...plans].sort(
|
||||
(a, b) => a.plan.display_order - b.plan.display_order
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
{/* Billing Toggle */}
|
||||
<div className="flex justify-center mb-12">
|
||||
<div className="bg-gray-100 dark:bg-gray-800 p-1 rounded-lg inline-flex">
|
||||
<button
|
||||
onClick={() => setBillingPeriod('monthly')}
|
||||
className={`px-6 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||
billingPeriod === 'monthly'
|
||||
? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
|
||||
}`}
|
||||
>
|
||||
{t('marketing.pricing.monthly', 'Monthly')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setBillingPeriod('annual')}
|
||||
className={`px-6 py-2 rounded-md text-sm font-medium transition-colors ${
|
||||
billingPeriod === 'annual'
|
||||
? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
|
||||
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
|
||||
}`}
|
||||
>
|
||||
{t('marketing.pricing.annual', 'Annual')}
|
||||
<span className="ml-2 text-xs text-green-600 dark:text-green-400 font-semibold">
|
||||
{t('marketing.pricing.savePercent', 'Save ~17%')}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Plans Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
{sortedPlans.map((planVersion) => (
|
||||
<PlanCard
|
||||
key={planVersion.id}
|
||||
planVersion={planVersion}
|
||||
billingPeriod={billingPeriod}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
interface PlanCardProps {
|
||||
planVersion: PublicPlanVersion;
|
||||
billingPeriod: 'monthly' | 'annual';
|
||||
}
|
||||
|
||||
const PlanCard: React.FC<PlanCardProps> = ({ planVersion, billingPeriod }) => {
|
||||
const { t } = useTranslation();
|
||||
const { plan, is_most_popular, show_price, marketing_features, trial_days } = planVersion;
|
||||
|
||||
const price =
|
||||
billingPeriod === 'annual'
|
||||
? planVersion.price_yearly_cents
|
||||
: planVersion.price_monthly_cents;
|
||||
|
||||
const isEnterprise = !show_price || plan.code === 'enterprise';
|
||||
const isFree = price === 0 && plan.code === 'free';
|
||||
|
||||
// Determine CTA
|
||||
const ctaLink = isEnterprise ? '/contact' : `/signup?plan=${plan.code}`;
|
||||
const ctaText = isEnterprise
|
||||
? t('marketing.pricing.contactSales', 'Contact Sales')
|
||||
: isFree
|
||||
? t('marketing.pricing.getStartedFree', 'Get Started Free')
|
||||
: t('marketing.pricing.startTrial', 'Start Free Trial');
|
||||
|
||||
if (is_most_popular) {
|
||||
return (
|
||||
<div className="relative flex flex-col p-6 bg-brand-600 rounded-2xl shadow-xl shadow-brand-600/20 transform lg:scale-105 z-10">
|
||||
{/* Most Popular Badge */}
|
||||
<div className="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-1 bg-brand-500 text-white text-xs font-semibold rounded-full whitespace-nowrap">
|
||||
{t('marketing.pricing.mostPopular', 'Most Popular')}
|
||||
</div>
|
||||
|
||||
{/* Header */}
|
||||
<div className="mb-4">
|
||||
<h3 className="text-lg font-bold text-white mb-1">{plan.name}</h3>
|
||||
<p className="text-brand-100 text-sm">{plan.description}</p>
|
||||
</div>
|
||||
|
||||
{/* Price */}
|
||||
<div className="mb-4">
|
||||
{isEnterprise ? (
|
||||
<span className="text-3xl font-bold text-white">
|
||||
{t('marketing.pricing.custom', 'Custom')}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-4xl font-bold text-white">
|
||||
{formatPrice(price)}
|
||||
</span>
|
||||
<span className="text-brand-200 ml-1 text-sm">
|
||||
{billingPeriod === 'annual'
|
||||
? t('marketing.pricing.perYear', '/year')
|
||||
: t('marketing.pricing.perMonth', '/month')}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{trial_days > 0 && !isFree && (
|
||||
<div className="mt-1 text-xs text-brand-100">
|
||||
{t('marketing.pricing.trialDays', '{{days}}-day free trial', {
|
||||
days: trial_days,
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Features */}
|
||||
<ul className="flex-1 space-y-2 mb-6">
|
||||
{marketing_features.map((feature, index) => (
|
||||
<li key={index} className="flex items-start gap-2">
|
||||
<Check className="h-4 w-4 text-brand-200 flex-shrink-0 mt-0.5" />
|
||||
<span className="text-white text-sm">{feature}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{/* CTA */}
|
||||
<Link
|
||||
to={ctaLink}
|
||||
className="block w-full py-3 px-4 text-center text-sm font-semibold text-brand-600 bg-white rounded-xl hover:bg-brand-50 transition-colors"
|
||||
>
|
||||
{ctaText}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative flex flex-col p-6 bg-white dark:bg-gray-800 rounded-2xl border border-gray-200 dark:border-gray-700 shadow-sm">
|
||||
{/* Header */}
|
||||
<div className="mb-4">
|
||||
<h3 className="text-lg font-bold text-gray-900 dark:text-white mb-1">
|
||||
{plan.name}
|
||||
</h3>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">
|
||||
{plan.description}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Price */}
|
||||
<div className="mb-4">
|
||||
{isEnterprise ? (
|
||||
<span className="text-3xl font-bold text-gray-900 dark:text-white">
|
||||
{t('marketing.pricing.custom', 'Custom')}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-4xl font-bold text-gray-900 dark:text-white">
|
||||
{formatPrice(price)}
|
||||
</span>
|
||||
<span className="text-gray-500 dark:text-gray-400 ml-1 text-sm">
|
||||
{billingPeriod === 'annual'
|
||||
? t('marketing.pricing.perYear', '/year')
|
||||
: t('marketing.pricing.perMonth', '/month')}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{trial_days > 0 && !isFree && (
|
||||
<div className="mt-1 text-xs text-brand-600 dark:text-brand-400">
|
||||
{t('marketing.pricing.trialDays', '{{days}}-day free trial', {
|
||||
days: trial_days,
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{isFree && (
|
||||
<div className="mt-1 text-xs text-green-600 dark:text-green-400">
|
||||
{t('marketing.pricing.freeForever', 'Free forever')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Features */}
|
||||
<ul className="flex-1 space-y-2 mb-6">
|
||||
{marketing_features.map((feature, index) => (
|
||||
<li key={index} className="flex items-start gap-2">
|
||||
<Check className="h-4 w-4 text-brand-600 dark:text-brand-400 flex-shrink-0 mt-0.5" />
|
||||
<span className="text-gray-700 dark:text-gray-300 text-sm">{feature}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{/* CTA */}
|
||||
<Link
|
||||
to={ctaLink}
|
||||
className={`block w-full py-3 px-4 text-center text-sm font-semibold rounded-xl transition-colors ${
|
||||
isFree
|
||||
? 'bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-600'
|
||||
: 'bg-brand-50 dark:bg-brand-900/30 text-brand-600 hover:bg-brand-100 dark:hover:bg-brand-900/50'
|
||||
}`}
|
||||
>
|
||||
{ctaText}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DynamicPricingCards;
|
||||
251
frontend/src/components/marketing/FeatureComparisonTable.tsx
Normal file
251
frontend/src/components/marketing/FeatureComparisonTable.tsx
Normal file
@@ -0,0 +1,251 @@
|
||||
import React from 'react';
|
||||
import { Check, X, Minus, Loader2 } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
usePublicPlans,
|
||||
PublicPlanVersion,
|
||||
getPlanFeatureValue,
|
||||
formatLimit,
|
||||
} from '../../hooks/usePublicPlans';
|
||||
|
||||
// Feature categories for the comparison table
|
||||
const FEATURE_CATEGORIES = [
|
||||
{
|
||||
key: 'limits',
|
||||
features: [
|
||||
{ code: 'max_users', label: 'Team members' },
|
||||
{ code: 'max_resources', label: 'Resources' },
|
||||
{ code: 'max_locations', label: 'Locations' },
|
||||
{ code: 'max_services', label: 'Services' },
|
||||
{ code: 'max_customers', label: 'Customers' },
|
||||
{ code: 'max_appointments_per_month', label: 'Appointments/month' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'communication',
|
||||
features: [
|
||||
{ code: 'email_enabled', label: 'Email notifications' },
|
||||
{ code: 'max_email_per_month', label: 'Emails/month' },
|
||||
{ code: 'sms_enabled', label: 'SMS reminders' },
|
||||
{ code: 'max_sms_per_month', label: 'SMS/month' },
|
||||
{ code: 'masked_calling_enabled', label: 'Masked calling' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'booking',
|
||||
features: [
|
||||
{ code: 'online_booking', label: 'Online booking' },
|
||||
{ code: 'recurring_appointments', label: 'Recurring appointments' },
|
||||
{ code: 'payment_processing', label: 'Accept payments' },
|
||||
{ code: 'mobile_app_access', label: 'Mobile app' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'integrations',
|
||||
features: [
|
||||
{ code: 'integrations_enabled', label: 'Third-party integrations' },
|
||||
{ code: 'api_access', label: 'API access' },
|
||||
{ code: 'max_api_calls_per_day', label: 'API calls/day' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'branding',
|
||||
features: [
|
||||
{ code: 'custom_domain', label: 'Custom domain' },
|
||||
{ code: 'custom_branding', label: 'Custom branding' },
|
||||
{ code: 'remove_branding', label: 'Remove "Powered by"' },
|
||||
{ code: 'white_label', label: 'White label' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'enterprise',
|
||||
features: [
|
||||
{ code: 'multi_location', label: 'Multi-location management' },
|
||||
{ code: 'team_permissions', label: 'Team permissions' },
|
||||
{ code: 'audit_logs', label: 'Audit logs' },
|
||||
{ code: 'advanced_reporting', label: 'Advanced analytics' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'support',
|
||||
features: [
|
||||
{ code: 'priority_support', label: 'Priority support' },
|
||||
{ code: 'dedicated_account_manager', label: 'Dedicated account manager' },
|
||||
{ code: 'sla_guarantee', label: 'SLA guarantee' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'storage',
|
||||
features: [
|
||||
{ code: 'max_storage_mb', label: 'File storage' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
interface FeatureComparisonTableProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const FeatureComparisonTable: React.FC<FeatureComparisonTableProps> = ({
|
||||
className = '',
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { data: plans, isLoading, error } = usePublicPlans();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-brand-600" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !plans || plans.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Sort plans by display_order
|
||||
const sortedPlans = [...plans].sort(
|
||||
(a, b) => a.plan.display_order - b.plan.display_order
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={`overflow-x-auto ${className}`}>
|
||||
<table className="w-full min-w-[800px]">
|
||||
{/* Header */}
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="text-left py-4 px-4 text-sm font-medium text-gray-500 dark:text-gray-400 border-b border-gray-200 dark:border-gray-700 w-64">
|
||||
{t('marketing.pricing.featureComparison.features', 'Features')}
|
||||
</th>
|
||||
{sortedPlans.map((planVersion) => (
|
||||
<th
|
||||
key={planVersion.id}
|
||||
className={`text-center py-4 px-4 text-sm font-semibold border-b border-gray-200 dark:border-gray-700 ${
|
||||
planVersion.is_most_popular
|
||||
? 'text-brand-600 dark:text-brand-400 bg-brand-50 dark:bg-brand-900/20'
|
||||
: 'text-gray-900 dark:text-white'
|
||||
}`}
|
||||
>
|
||||
{planVersion.plan.name}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{FEATURE_CATEGORIES.map((category) => (
|
||||
<React.Fragment key={category.key}>
|
||||
{/* Category Header */}
|
||||
<tr>
|
||||
<td
|
||||
colSpan={sortedPlans.length + 1}
|
||||
className="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-800/50"
|
||||
>
|
||||
{t(
|
||||
`marketing.pricing.featureComparison.categories.${category.key}`,
|
||||
category.key.charAt(0).toUpperCase() + category.key.slice(1)
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
{/* Features */}
|
||||
{category.features.map((feature) => (
|
||||
<tr
|
||||
key={feature.code}
|
||||
className="border-b border-gray-100 dark:border-gray-800"
|
||||
>
|
||||
<td className="py-3 px-4 text-sm text-gray-700 dark:text-gray-300">
|
||||
{t(
|
||||
`marketing.pricing.featureComparison.features.${feature.code}`,
|
||||
feature.label
|
||||
)}
|
||||
</td>
|
||||
{sortedPlans.map((planVersion) => (
|
||||
<td
|
||||
key={`${planVersion.id}-${feature.code}`}
|
||||
className={`py-3 px-4 text-center ${
|
||||
planVersion.is_most_popular
|
||||
? 'bg-brand-50/50 dark:bg-brand-900/10'
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
<FeatureValue
|
||||
planVersion={planVersion}
|
||||
featureCode={feature.code}
|
||||
/>
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
interface FeatureValueProps {
|
||||
planVersion: PublicPlanVersion;
|
||||
featureCode: string;
|
||||
}
|
||||
|
||||
const FeatureValue: React.FC<FeatureValueProps> = ({
|
||||
planVersion,
|
||||
featureCode,
|
||||
}) => {
|
||||
const value = getPlanFeatureValue(planVersion, featureCode);
|
||||
|
||||
// Handle null/undefined - feature not set
|
||||
if (value === null || value === undefined) {
|
||||
return (
|
||||
<X className="w-5 h-5 text-gray-300 dark:text-gray-600 mx-auto" />
|
||||
);
|
||||
}
|
||||
|
||||
// Boolean feature
|
||||
if (typeof value === 'boolean') {
|
||||
return value ? (
|
||||
<Check className="w-5 h-5 text-green-500 mx-auto" />
|
||||
) : (
|
||||
<X className="w-5 h-5 text-gray-300 dark:text-gray-600 mx-auto" />
|
||||
);
|
||||
}
|
||||
|
||||
// Integer feature (limit)
|
||||
if (typeof value === 'number') {
|
||||
// Special handling for storage (convert MB to GB if > 1000)
|
||||
if (featureCode === 'max_storage_mb') {
|
||||
if (value === 0) {
|
||||
return (
|
||||
<span className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
Unlimited
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (value >= 1000) {
|
||||
return (
|
||||
<span className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{(value / 1000).toFixed(0)} GB
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{value} MB
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// Regular limit display
|
||||
return (
|
||||
<span className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{formatLimit(value)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// Fallback
|
||||
return <Minus className="w-5 h-5 text-gray-300 dark:text-gray-600 mx-auto" />;
|
||||
};
|
||||
|
||||
export default FeatureComparisonTable;
|
||||
312
frontend/src/components/platform/DynamicFeaturesEditor.tsx
Normal file
312
frontend/src/components/platform/DynamicFeaturesEditor.tsx
Normal file
@@ -0,0 +1,312 @@
|
||||
/**
|
||||
* DynamicFeaturesEditor
|
||||
*
|
||||
* A dynamic component that loads features from the billing system API
|
||||
* and renders them as toggles/inputs for editing business permissions.
|
||||
*
|
||||
* This is the DYNAMIC version that gets features from the billing catalog,
|
||||
* which is the single source of truth. When you add a new feature to the
|
||||
* billing system, it automatically appears here.
|
||||
*/
|
||||
|
||||
import React, { useMemo } from 'react';
|
||||
import { Key, AlertCircle } from 'lucide-react';
|
||||
import { useBillingFeatures, BillingFeature, FEATURE_CATEGORY_META } from '../../hooks/useBillingPlans';
|
||||
|
||||
export interface DynamicFeaturesEditorProps {
|
||||
/**
|
||||
* Current feature values mapped by tenant_field_name
|
||||
* For booleans: { can_use_sms_reminders: true, can_api_access: false, ... }
|
||||
* For integers: { max_users: 10, max_resources: 5, ... }
|
||||
*/
|
||||
values: Record<string, boolean | number | null>;
|
||||
|
||||
/**
|
||||
* Callback when a feature value changes
|
||||
* @param fieldName - The tenant_field_name of the feature
|
||||
* @param value - The new value (boolean for toggles, number for limits)
|
||||
*/
|
||||
onChange: (fieldName: string, value: boolean | number | null) => void;
|
||||
|
||||
/**
|
||||
* Optional: Only show features in these categories
|
||||
*/
|
||||
categories?: BillingFeature['category'][];
|
||||
|
||||
/**
|
||||
* Optional: Only show boolean or integer features
|
||||
*/
|
||||
featureType?: 'boolean' | 'integer';
|
||||
|
||||
/**
|
||||
* Optional: Exclude features by code
|
||||
*/
|
||||
excludeCodes?: string[];
|
||||
|
||||
/**
|
||||
* Show section header (default: true)
|
||||
*/
|
||||
showHeader?: boolean;
|
||||
|
||||
/**
|
||||
* Custom header title
|
||||
*/
|
||||
headerTitle?: string;
|
||||
|
||||
/**
|
||||
* Show descriptions under labels (default: false)
|
||||
*/
|
||||
showDescriptions?: boolean;
|
||||
|
||||
/**
|
||||
* Number of columns (default: 3)
|
||||
*/
|
||||
columns?: 2 | 3 | 4;
|
||||
}
|
||||
|
||||
const DynamicFeaturesEditor: React.FC<DynamicFeaturesEditorProps> = ({
|
||||
values,
|
||||
onChange,
|
||||
categories,
|
||||
featureType,
|
||||
excludeCodes = [],
|
||||
showHeader = true,
|
||||
headerTitle = 'Features & Permissions',
|
||||
showDescriptions = false,
|
||||
columns = 3,
|
||||
}) => {
|
||||
const { data: features, isLoading, error } = useBillingFeatures();
|
||||
|
||||
// Debug logging
|
||||
console.log('[DynamicFeaturesEditor] Features:', features?.length, 'Loading:', isLoading, 'Error:', error);
|
||||
|
||||
// Filter and group features
|
||||
const groupedFeatures = useMemo(() => {
|
||||
if (!features) {
|
||||
console.log('[DynamicFeaturesEditor] No features data');
|
||||
return {};
|
||||
}
|
||||
|
||||
// Filter features
|
||||
const filtered = features.filter(f => {
|
||||
if (excludeCodes.includes(f.code)) return false;
|
||||
if (categories && !categories.includes(f.category)) return false;
|
||||
if (featureType && f.feature_type !== featureType) return false;
|
||||
if (!f.is_overridable) return false; // Skip non-overridable features
|
||||
if (!f.tenant_field_name) return false; // Skip features without tenant field
|
||||
return true;
|
||||
});
|
||||
console.log('[DynamicFeaturesEditor] Filtered features:', filtered.length, 'featureType:', featureType);
|
||||
|
||||
// Group by category
|
||||
const groups: Record<string, BillingFeature[]> = {};
|
||||
for (const feature of filtered) {
|
||||
if (!groups[feature.category]) {
|
||||
groups[feature.category] = [];
|
||||
}
|
||||
groups[feature.category].push(feature);
|
||||
}
|
||||
|
||||
// Sort features within each category by display_order
|
||||
for (const category of Object.keys(groups)) {
|
||||
groups[category].sort((a, b) => a.display_order - b.display_order);
|
||||
}
|
||||
|
||||
return groups;
|
||||
}, [features, categories, featureType, excludeCodes]);
|
||||
|
||||
// Sort categories by their order
|
||||
const sortedCategories = useMemo(() => {
|
||||
return Object.keys(groupedFeatures).sort(
|
||||
(a, b) => (FEATURE_CATEGORY_META[a as BillingFeature['category']]?.order ?? 99) -
|
||||
(FEATURE_CATEGORY_META[b as BillingFeature['category']]?.order ?? 99)
|
||||
) as BillingFeature['category'][];
|
||||
}, [groupedFeatures]);
|
||||
|
||||
// Check if a dependent feature should be disabled
|
||||
const isDependencyDisabled = (feature: BillingFeature): boolean => {
|
||||
if (!feature.depends_on_code) return false;
|
||||
const parentFeature = features?.find(f => f.code === feature.depends_on_code);
|
||||
if (!parentFeature) return false;
|
||||
const parentValue = values[parentFeature.tenant_field_name];
|
||||
return !parentValue;
|
||||
};
|
||||
|
||||
// Handle value change
|
||||
const handleChange = (feature: BillingFeature, newValue: boolean | number | null) => {
|
||||
onChange(feature.tenant_field_name, newValue);
|
||||
|
||||
// If disabling a parent feature, also disable dependents
|
||||
if (feature.feature_type === 'boolean' && !newValue) {
|
||||
const dependents = features?.filter(f => f.depends_on_code === feature.code) ?? [];
|
||||
for (const dep of dependents) {
|
||||
if (values[dep.tenant_field_name]) {
|
||||
onChange(dep.tenant_field_name, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const gridCols = {
|
||||
2: 'grid-cols-2',
|
||||
3: 'grid-cols-3',
|
||||
4: 'grid-cols-4',
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{showHeader && (
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<Key size={16} className="text-purple-500" />
|
||||
{headerTitle}
|
||||
</h3>
|
||||
)}
|
||||
<div className="animate-pulse space-y-3">
|
||||
<div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-24"></div>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{[1, 2, 3, 4, 5, 6].map(i => (
|
||||
<div key={i} className="h-12 bg-gray-100 dark:bg-gray-800 rounded"></div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{showHeader && (
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<Key size={16} className="text-purple-500" />
|
||||
{headerTitle}
|
||||
</h3>
|
||||
)}
|
||||
<div className="flex items-center gap-2 text-amber-600 dark:text-amber-400">
|
||||
<AlertCircle size={16} />
|
||||
<span className="text-sm">Failed to load features from billing system</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{showHeader && (
|
||||
<>
|
||||
<h3 className="text-sm font-medium text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<Key size={16} className="text-purple-500" />
|
||||
{headerTitle}
|
||||
</h3>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
Control which features are available. Features are loaded from the billing system.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{sortedCategories.map(category => {
|
||||
const categoryFeatures = groupedFeatures[category];
|
||||
if (!categoryFeatures || categoryFeatures.length === 0) return null;
|
||||
|
||||
const categoryMeta = FEATURE_CATEGORY_META[category];
|
||||
|
||||
return (
|
||||
<div key={category}>
|
||||
<h4 className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">
|
||||
{categoryMeta?.label || category}
|
||||
</h4>
|
||||
<div className={`grid ${gridCols[columns]} gap-3`}>
|
||||
{categoryFeatures.map(feature => {
|
||||
const isDisabled = isDependencyDisabled(feature);
|
||||
const currentValue = values[feature.tenant_field_name];
|
||||
|
||||
if (feature.feature_type === 'boolean') {
|
||||
const isChecked = currentValue === true;
|
||||
|
||||
return (
|
||||
<label
|
||||
key={feature.code}
|
||||
className={`flex items-start gap-2 p-2 border border-gray-200 dark:border-gray-700 rounded-lg ${
|
||||
isDisabled
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-700/50 cursor-pointer'
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isChecked}
|
||||
onChange={(e) => handleChange(feature, e.target.checked)}
|
||||
disabled={isDisabled}
|
||||
className="mt-0.5 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500 disabled:opacity-50"
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300 block">
|
||||
{feature.name}
|
||||
</span>
|
||||
{showDescriptions && feature.description && (
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 block mt-0.5">
|
||||
{feature.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
// Integer feature (limit)
|
||||
const intValue = typeof currentValue === 'number' ? currentValue : 0;
|
||||
const isUnlimited = currentValue === null || currentValue === -1;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={feature.code}
|
||||
className="p-2 border border-gray-200 dark:border-gray-700 rounded-lg"
|
||||
>
|
||||
<label className="text-sm text-gray-700 dark:text-gray-300 block mb-1">
|
||||
{feature.name}
|
||||
</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
min="-1"
|
||||
value={isUnlimited ? -1 : intValue}
|
||||
onChange={(e) => {
|
||||
const val = parseInt(e.target.value);
|
||||
handleChange(feature, val === -1 ? null : val);
|
||||
}}
|
||||
className="w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-1 focus:ring-indigo-500"
|
||||
/>
|
||||
</div>
|
||||
{showDescriptions && (
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 block mt-1">
|
||||
{feature.description} (-1 = unlimited)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Show dependency hint for plugins category */}
|
||||
{category === 'plugins' && (
|
||||
(() => {
|
||||
const pluginsFeature = categoryFeatures.find(f => f.code === 'can_use_plugins');
|
||||
if (pluginsFeature && !values[pluginsFeature.tenant_field_name]) {
|
||||
return (
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400 mt-2">
|
||||
Enable "Use Plugins" to allow dependent features
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})()
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DynamicFeaturesEditor;
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
CalendarDays,
|
||||
CalendarRange,
|
||||
Loader2,
|
||||
MapPin,
|
||||
} from 'lucide-react';
|
||||
import Portal from '../Portal';
|
||||
import {
|
||||
@@ -40,8 +41,11 @@ import {
|
||||
Holiday,
|
||||
Resource,
|
||||
TimeBlockListItem,
|
||||
Location,
|
||||
} from '../../types';
|
||||
import { formatLocalDate } from '../../utils/dateUtils';
|
||||
import { LocationSelector, useShouldShowLocationSelector, useAutoSelectLocation } from '../LocationSelector';
|
||||
import { usePlanFeatures } from '../../hooks/usePlanFeatures';
|
||||
|
||||
// Preset block types
|
||||
const PRESETS = [
|
||||
@@ -155,6 +159,7 @@ interface TimeBlockCreatorModalProps {
|
||||
editingBlock?: TimeBlockListItem | null;
|
||||
holidays: Holiday[];
|
||||
resources: Resource[];
|
||||
locations?: Location[];
|
||||
isResourceLevel?: boolean;
|
||||
/** Staff mode: hides level selector, locks to resource, pre-selects resource */
|
||||
staffMode?: boolean;
|
||||
@@ -162,6 +167,9 @@ interface TimeBlockCreatorModalProps {
|
||||
staffResourceId?: string | number | null;
|
||||
}
|
||||
|
||||
// Block level types for the three-tier system
|
||||
type BlockLevel = 'business' | 'location' | 'resource';
|
||||
|
||||
type Step = 'preset' | 'details' | 'schedule' | 'review';
|
||||
|
||||
const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
@@ -172,6 +180,7 @@ const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
editingBlock,
|
||||
holidays,
|
||||
resources,
|
||||
locations = [],
|
||||
isResourceLevel: initialIsResourceLevel = false,
|
||||
staffMode = false,
|
||||
staffResourceId = null,
|
||||
@@ -181,6 +190,18 @@ const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
const [selectedPreset, setSelectedPreset] = useState<string | null>(null);
|
||||
const [isResourceLevel, setIsResourceLevel] = useState(initialIsResourceLevel);
|
||||
|
||||
// Multi-location support
|
||||
const { canUse } = usePlanFeatures();
|
||||
const hasMultiLocation = canUse('multi_location');
|
||||
const showLocationSelector = useShouldShowLocationSelector();
|
||||
const [blockLevel, setBlockLevel] = useState<BlockLevel>(
|
||||
initialIsResourceLevel ? 'resource' : 'business'
|
||||
);
|
||||
const [locationId, setLocationId] = useState<number | null>(null);
|
||||
|
||||
// Auto-select location when only one exists
|
||||
useAutoSelectLocation(locationId, setLocationId);
|
||||
|
||||
// Form state
|
||||
const [title, setTitle] = useState(editingBlock?.title || '');
|
||||
const [description, setDescription] = useState(editingBlock?.description || '');
|
||||
@@ -233,7 +254,21 @@ const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
setStartTime(editingBlock.start_time || '09:00');
|
||||
setEndTime(editingBlock.end_time || '17:00');
|
||||
setResourceId(editingBlock.resource || null);
|
||||
setIsResourceLevel(!!editingBlock.resource); // Set level based on whether block has a resource
|
||||
setLocationId(editingBlock.location ?? null);
|
||||
// Determine block level based on existing data
|
||||
if (editingBlock.is_business_wide) {
|
||||
setBlockLevel('business');
|
||||
setIsResourceLevel(false);
|
||||
} else if (editingBlock.location && !editingBlock.resource) {
|
||||
setBlockLevel('location');
|
||||
setIsResourceLevel(false);
|
||||
} else if (editingBlock.resource) {
|
||||
setBlockLevel('resource');
|
||||
setIsResourceLevel(true);
|
||||
} else {
|
||||
setBlockLevel('business');
|
||||
setIsResourceLevel(false);
|
||||
}
|
||||
// Parse dates if available
|
||||
if (editingBlock.start_date) {
|
||||
const startDate = new Date(editingBlock.start_date);
|
||||
@@ -288,8 +323,10 @@ const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
setHolidayCodes([]);
|
||||
setRecurrenceStart('');
|
||||
setRecurrenceEnd('');
|
||||
setLocationId(null);
|
||||
// In staff mode, always resource-level
|
||||
setIsResourceLevel(staffMode ? true : initialIsResourceLevel);
|
||||
setBlockLevel(staffMode ? 'resource' : (initialIsResourceLevel ? 'resource' : 'business'));
|
||||
}
|
||||
}
|
||||
}, [isOpen, editingBlock, initialIsResourceLevel, staffMode, staffResourceId]);
|
||||
@@ -381,12 +418,37 @@ const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
// In staff mode, always use the staff's resource ID
|
||||
const effectiveResourceId = staffMode ? staffResourceId : resourceId;
|
||||
|
||||
// Determine location and resource based on block level
|
||||
let effectiveLocation: number | null = null;
|
||||
let effectiveResource: string | number | null = null;
|
||||
let isBusinessWide = false;
|
||||
|
||||
switch (blockLevel) {
|
||||
case 'business':
|
||||
isBusinessWide = true;
|
||||
effectiveLocation = null;
|
||||
effectiveResource = null;
|
||||
break;
|
||||
case 'location':
|
||||
isBusinessWide = false;
|
||||
effectiveLocation = locationId;
|
||||
effectiveResource = null;
|
||||
break;
|
||||
case 'resource':
|
||||
isBusinessWide = false;
|
||||
effectiveLocation = locationId; // Resource blocks can optionally have a location
|
||||
effectiveResource = effectiveResourceId;
|
||||
break;
|
||||
}
|
||||
|
||||
const baseData: any = {
|
||||
description: description || undefined,
|
||||
block_type: blockType,
|
||||
recurrence_type: recurrenceType,
|
||||
all_day: allDay,
|
||||
resource: isResourceLevel ? effectiveResourceId : null,
|
||||
resource: effectiveResource,
|
||||
location: effectiveLocation,
|
||||
is_business_wide: isBusinessWide,
|
||||
};
|
||||
|
||||
if (!allDay) {
|
||||
@@ -441,6 +503,8 @@ const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
if (!title.trim()) return false;
|
||||
// In staff mode, resource is auto-selected; otherwise check if selected
|
||||
if (isResourceLevel && !staffMode && !resourceId) return false;
|
||||
// Location is required when blockLevel is 'location'
|
||||
if (blockLevel === 'location' && !locationId) return false;
|
||||
return true;
|
||||
case 'schedule':
|
||||
if (recurrenceType === 'NONE' && selectedDates.length === 0) return false;
|
||||
@@ -577,48 +641,87 @@ const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
<label className="block text-base font-semibold text-gray-900 dark:text-white mb-3">
|
||||
Block Level
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className={`grid gap-4 ${showLocationSelector ? 'grid-cols-3' : 'grid-cols-2'}`}>
|
||||
{/* Business-wide option */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setBlockLevel('business');
|
||||
setIsResourceLevel(false);
|
||||
setResourceId(null);
|
||||
setLocationId(null);
|
||||
}}
|
||||
className={`p-4 rounded-xl border-2 transition-all text-left ${
|
||||
!isResourceLevel
|
||||
blockLevel === 'business'
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-900/30'
|
||||
: 'border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`p-2 rounded-lg ${!isResourceLevel ? 'bg-brand-100 dark:bg-brand-800' : 'bg-gray-100 dark:bg-gray-700'}`}>
|
||||
<Building2 size={20} className={!isResourceLevel ? 'text-brand-600 dark:text-brand-400' : 'text-gray-500 dark:text-gray-400'} />
|
||||
<div className={`p-2 rounded-lg ${blockLevel === 'business' ? 'bg-brand-100 dark:bg-brand-800' : 'bg-gray-100 dark:bg-gray-700'}`}>
|
||||
<Building2 size={20} className={blockLevel === 'business' ? 'text-brand-600 dark:text-brand-400' : 'text-gray-500 dark:text-gray-400'} />
|
||||
</div>
|
||||
<div>
|
||||
<p className={`font-semibold ${!isResourceLevel ? 'text-brand-700 dark:text-brand-300' : 'text-gray-900 dark:text-white'}`}>
|
||||
<p className={`font-semibold ${blockLevel === 'business' ? 'text-brand-700 dark:text-brand-300' : 'text-gray-900 dark:text-white'}`}>
|
||||
Business-wide
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Affects all resources
|
||||
{showLocationSelector ? 'All locations & resources' : 'Affects all resources'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Location-wide option - only show when multi-location is enabled */}
|
||||
{showLocationSelector && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setBlockLevel('location');
|
||||
setIsResourceLevel(false);
|
||||
setResourceId(null);
|
||||
}}
|
||||
className={`p-4 rounded-xl border-2 transition-all text-left ${
|
||||
blockLevel === 'location'
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-900/30'
|
||||
: 'border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`p-2 rounded-lg ${blockLevel === 'location' ? 'bg-brand-100 dark:bg-brand-800' : 'bg-gray-100 dark:bg-gray-700'}`}>
|
||||
<MapPin size={20} className={blockLevel === 'location' ? 'text-brand-600 dark:text-brand-400' : 'text-gray-500 dark:text-gray-400'} />
|
||||
</div>
|
||||
<div>
|
||||
<p className={`font-semibold ${blockLevel === 'location' ? 'text-brand-700 dark:text-brand-300' : 'text-gray-900 dark:text-white'}`}>
|
||||
Specific Location
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
All resources at one location
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Resource-specific option */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsResourceLevel(true)}
|
||||
onClick={() => {
|
||||
setBlockLevel('resource');
|
||||
setIsResourceLevel(true);
|
||||
}}
|
||||
className={`p-4 rounded-xl border-2 transition-all text-left ${
|
||||
isResourceLevel
|
||||
blockLevel === 'resource'
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-900/30'
|
||||
: 'border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`p-2 rounded-lg ${isResourceLevel ? 'bg-brand-100 dark:bg-brand-800' : 'bg-gray-100 dark:bg-gray-700'}`}>
|
||||
<User size={20} className={isResourceLevel ? 'text-brand-600 dark:text-brand-400' : 'text-gray-500 dark:text-gray-400'} />
|
||||
<div className={`p-2 rounded-lg ${blockLevel === 'resource' ? 'bg-brand-100 dark:bg-brand-800' : 'bg-gray-100 dark:bg-gray-700'}`}>
|
||||
<User size={20} className={blockLevel === 'resource' ? 'text-brand-600 dark:text-brand-400' : 'text-gray-500 dark:text-gray-400'} />
|
||||
</div>
|
||||
<div>
|
||||
<p className={`font-semibold ${isResourceLevel ? 'text-brand-700 dark:text-brand-300' : 'text-gray-900 dark:text-white'}`}>
|
||||
<p className={`font-semibold ${blockLevel === 'resource' ? 'text-brand-700 dark:text-brand-300' : 'text-gray-900 dark:text-white'}`}>
|
||||
Specific Resource
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
@@ -628,6 +731,18 @@ const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Location Selector - show when location-level is selected */}
|
||||
{blockLevel === 'location' && showLocationSelector && (
|
||||
<div className="mt-4">
|
||||
<LocationSelector
|
||||
value={locationId}
|
||||
onChange={setLocationId}
|
||||
label="Location"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -661,20 +776,32 @@ const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
|
||||
{/* Resource (if resource-level) - Hidden in staff mode since it's auto-selected */}
|
||||
{isResourceLevel && !staffMode && (
|
||||
<div>
|
||||
<label className="block text-base font-semibold text-gray-900 dark:text-white mb-2">
|
||||
Resource
|
||||
</label>
|
||||
<select
|
||||
value={resourceId || ''}
|
||||
onChange={(e) => setResourceId(e.target.value || null)}
|
||||
className="w-full px-4 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 transition-colors"
|
||||
>
|
||||
<option value="">Select a resource...</option>
|
||||
{resources.map((r) => (
|
||||
<option key={r.id} value={r.id}>{r.name}</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-base font-semibold text-gray-900 dark:text-white mb-2">
|
||||
Resource
|
||||
</label>
|
||||
<select
|
||||
value={resourceId || ''}
|
||||
onChange={(e) => setResourceId(e.target.value || null)}
|
||||
className="w-full px-4 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-xl bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 transition-colors"
|
||||
>
|
||||
<option value="">Select a resource...</option>
|
||||
{resources.map((r) => (
|
||||
<option key={r.id} value={r.id}>{r.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Optional location for resource-level blocks when multi-location is enabled */}
|
||||
{showLocationSelector && (
|
||||
<LocationSelector
|
||||
value={locationId}
|
||||
onChange={setLocationId}
|
||||
label="Location (optional)"
|
||||
hint="Optionally limit this block to a specific location"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1207,6 +1334,40 @@ const TimeBlockCreatorModal: React.FC<TimeBlockCreatorModalProps> = ({
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
{/* Block Level - show when multi-location is enabled or not in staff mode */}
|
||||
{!staffMode && (
|
||||
<div className="flex justify-between py-2 border-b border-gray-200 dark:border-gray-700">
|
||||
<dt className="text-gray-500 dark:text-gray-400">Applies To</dt>
|
||||
<dd className="font-medium text-gray-900 dark:text-white">
|
||||
<span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-sm ${
|
||||
blockLevel === 'business'
|
||||
? 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300'
|
||||
: blockLevel === 'location'
|
||||
? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300'
|
||||
: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300'
|
||||
}`}>
|
||||
{blockLevel === 'business' && <Building2 size={14} />}
|
||||
{blockLevel === 'location' && <MapPin size={14} />}
|
||||
{blockLevel === 'resource' && <User size={14} />}
|
||||
{blockLevel === 'business' && 'Business-wide'}
|
||||
{blockLevel === 'location' && 'Specific Location'}
|
||||
{blockLevel === 'resource' && 'Specific Resource'}
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Location - show when location is selected */}
|
||||
{(blockLevel === 'location' || (blockLevel === 'resource' && locationId)) && locationId && (
|
||||
<div className="flex justify-between py-2 border-b border-gray-200 dark:border-gray-700">
|
||||
<dt className="text-gray-500 dark:text-gray-400">Location</dt>
|
||||
<dd className="font-medium text-gray-900 dark:text-white">
|
||||
{locations.find(l => l.id === locationId)?.name || `Location ${locationId}`}
|
||||
</dd>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Resource - show for resource-level blocks */}
|
||||
{isResourceLevel && (resourceId || staffResourceId) && (
|
||||
<div className="flex justify-between py-2">
|
||||
<dt className="text-gray-500 dark:text-gray-400">Resource</dt>
|
||||
|
||||
105
frontend/src/components/ui/__tests__/Alert.test.tsx
Normal file
105
frontend/src/components/ui/__tests__/Alert.test.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { Alert, ErrorMessage, SuccessMessage, WarningMessage, InfoMessage } from '../Alert';
|
||||
|
||||
describe('Alert', () => {
|
||||
it('renders message', () => {
|
||||
render(<Alert variant="info" message="Test message" />);
|
||||
expect(screen.getByText('Test message')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders title when provided', () => {
|
||||
render(<Alert variant="info" message="Message" title="Title" />);
|
||||
expect(screen.getByText('Title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders message as ReactNode', () => {
|
||||
render(
|
||||
<Alert
|
||||
variant="info"
|
||||
message={<span data-testid="custom">Custom content</span>}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByTestId('custom')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('has alert role', () => {
|
||||
render(<Alert variant="info" message="Test" />);
|
||||
expect(screen.getByRole('alert')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders error variant', () => {
|
||||
render(<Alert variant="error" message="Error" />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('bg-red-50');
|
||||
});
|
||||
|
||||
it('renders success variant', () => {
|
||||
render(<Alert variant="success" message="Success" />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('bg-green-50');
|
||||
});
|
||||
|
||||
it('renders warning variant', () => {
|
||||
render(<Alert variant="warning" message="Warning" />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('bg-amber-50');
|
||||
});
|
||||
|
||||
it('renders info variant', () => {
|
||||
render(<Alert variant="info" message="Info" />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('bg-blue-50');
|
||||
});
|
||||
|
||||
it('shows dismiss button when onDismiss is provided', () => {
|
||||
const handleDismiss = vi.fn();
|
||||
render(<Alert variant="info" message="Test" onDismiss={handleDismiss} />);
|
||||
expect(screen.getByLabelText('Dismiss')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onDismiss when dismiss button clicked', () => {
|
||||
const handleDismiss = vi.fn();
|
||||
render(<Alert variant="info" message="Test" onDismiss={handleDismiss} />);
|
||||
fireEvent.click(screen.getByLabelText('Dismiss'));
|
||||
expect(handleDismiss).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not show dismiss button without onDismiss', () => {
|
||||
render(<Alert variant="info" message="Test" />);
|
||||
expect(screen.queryByLabelText('Dismiss')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(<Alert variant="info" message="Test" className="custom-class" />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('applies compact style', () => {
|
||||
render(<Alert variant="info" message="Test" compact />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('p-2');
|
||||
});
|
||||
|
||||
it('applies regular padding without compact', () => {
|
||||
render(<Alert variant="info" message="Test" />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('p-3');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Convenience components', () => {
|
||||
it('ErrorMessage renders error variant', () => {
|
||||
render(<ErrorMessage message="Error" />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('bg-red-50');
|
||||
});
|
||||
|
||||
it('SuccessMessage renders success variant', () => {
|
||||
render(<SuccessMessage message="Success" />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('bg-green-50');
|
||||
});
|
||||
|
||||
it('WarningMessage renders warning variant', () => {
|
||||
render(<WarningMessage message="Warning" />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('bg-amber-50');
|
||||
});
|
||||
|
||||
it('InfoMessage renders info variant', () => {
|
||||
render(<InfoMessage message="Info" />);
|
||||
expect(screen.getByRole('alert')).toHaveClass('bg-blue-50');
|
||||
});
|
||||
});
|
||||
76
frontend/src/components/ui/__tests__/Badge.test.tsx
Normal file
76
frontend/src/components/ui/__tests__/Badge.test.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { Badge } from '../Badge';
|
||||
|
||||
describe('Badge', () => {
|
||||
it('renders children', () => {
|
||||
render(<Badge>Test</Badge>);
|
||||
expect(screen.getByText('Test')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders default variant', () => {
|
||||
render(<Badge>Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('bg-gray-100');
|
||||
});
|
||||
|
||||
it('renders primary variant', () => {
|
||||
render(<Badge variant="primary">Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('bg-brand-100');
|
||||
});
|
||||
|
||||
it('renders success variant', () => {
|
||||
render(<Badge variant="success">Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('bg-green-100');
|
||||
});
|
||||
|
||||
it('renders warning variant', () => {
|
||||
render(<Badge variant="warning">Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('bg-amber-100');
|
||||
});
|
||||
|
||||
it('renders danger variant', () => {
|
||||
render(<Badge variant="danger">Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('bg-red-100');
|
||||
});
|
||||
|
||||
it('renders info variant', () => {
|
||||
render(<Badge variant="info">Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('bg-blue-100');
|
||||
});
|
||||
|
||||
it('applies small size', () => {
|
||||
render(<Badge size="sm">Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('text-xs');
|
||||
});
|
||||
|
||||
it('applies medium size', () => {
|
||||
render(<Badge size="md">Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('text-xs');
|
||||
});
|
||||
|
||||
it('applies large size', () => {
|
||||
render(<Badge size="lg">Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('text-sm');
|
||||
});
|
||||
|
||||
it('applies pill style', () => {
|
||||
render(<Badge pill>Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('rounded-full');
|
||||
});
|
||||
|
||||
it('applies rounded style by default', () => {
|
||||
render(<Badge>Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('rounded');
|
||||
});
|
||||
|
||||
it('renders dot indicator', () => {
|
||||
const { container } = render(<Badge dot>Test</Badge>);
|
||||
const dot = container.querySelector('.rounded-full');
|
||||
expect(dot).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(<Badge className="custom-class">Test</Badge>);
|
||||
expect(screen.getByText('Test').closest('span')).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
125
frontend/src/components/ui/__tests__/Button.test.tsx
Normal file
125
frontend/src/components/ui/__tests__/Button.test.tsx
Normal file
@@ -0,0 +1,125 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { Button, SubmitButton } from '../Button';
|
||||
|
||||
describe('Button', () => {
|
||||
it('renders children', () => {
|
||||
render(<Button>Click me</Button>);
|
||||
expect(screen.getByText('Click me')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles click events', () => {
|
||||
const handleClick = vi.fn();
|
||||
render(<Button onClick={handleClick}>Click me</Button>);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
expect(handleClick).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('is disabled when disabled prop is true', () => {
|
||||
render(<Button disabled>Click me</Button>);
|
||||
expect(screen.getByRole('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('is disabled when loading', () => {
|
||||
render(<Button isLoading>Click me</Button>);
|
||||
expect(screen.getByRole('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows loading spinner when loading', () => {
|
||||
render(<Button isLoading>Click me</Button>);
|
||||
const spinner = document.querySelector('.animate-spin');
|
||||
expect(spinner).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows loading text when loading', () => {
|
||||
render(<Button isLoading loadingText="Loading...">Click me</Button>);
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies primary variant by default', () => {
|
||||
render(<Button>Click me</Button>);
|
||||
expect(screen.getByRole('button')).toHaveClass('bg-brand-600');
|
||||
});
|
||||
|
||||
it('applies secondary variant', () => {
|
||||
render(<Button variant="secondary">Click me</Button>);
|
||||
expect(screen.getByRole('button')).toHaveClass('bg-gray-600');
|
||||
});
|
||||
|
||||
it('applies danger variant', () => {
|
||||
render(<Button variant="danger">Click me</Button>);
|
||||
expect(screen.getByRole('button')).toHaveClass('bg-red-600');
|
||||
});
|
||||
|
||||
it('applies success variant', () => {
|
||||
render(<Button variant="success">Click me</Button>);
|
||||
expect(screen.getByRole('button')).toHaveClass('bg-green-600');
|
||||
});
|
||||
|
||||
it('applies warning variant', () => {
|
||||
render(<Button variant="warning">Click me</Button>);
|
||||
expect(screen.getByRole('button')).toHaveClass('bg-amber-600');
|
||||
});
|
||||
|
||||
it('applies outline variant', () => {
|
||||
render(<Button variant="outline">Click me</Button>);
|
||||
expect(screen.getByRole('button')).toHaveClass('bg-transparent');
|
||||
});
|
||||
|
||||
it('applies ghost variant', () => {
|
||||
render(<Button variant="ghost">Click me</Button>);
|
||||
expect(screen.getByRole('button')).toHaveClass('bg-transparent');
|
||||
});
|
||||
|
||||
it('applies size classes', () => {
|
||||
render(<Button size="sm">Small</Button>);
|
||||
expect(screen.getByRole('button')).toHaveClass('px-3');
|
||||
});
|
||||
|
||||
it('applies full width', () => {
|
||||
render(<Button fullWidth>Full Width</Button>);
|
||||
expect(screen.getByRole('button')).toHaveClass('w-full');
|
||||
});
|
||||
|
||||
it('renders left icon', () => {
|
||||
render(<Button leftIcon={<span data-testid="left-icon">L</span>}>With Icon</Button>);
|
||||
expect(screen.getByTestId('left-icon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders right icon', () => {
|
||||
render(<Button rightIcon={<span data-testid="right-icon">R</span>}>With Icon</Button>);
|
||||
expect(screen.getByTestId('right-icon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(<Button className="custom-class">Click me</Button>);
|
||||
expect(screen.getByRole('button')).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
|
||||
describe('SubmitButton', () => {
|
||||
it('renders submit text by default', () => {
|
||||
render(<SubmitButton />);
|
||||
expect(screen.getByText('Save')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('has type submit', () => {
|
||||
render(<SubmitButton />);
|
||||
expect(screen.getByRole('button')).toHaveAttribute('type', 'submit');
|
||||
});
|
||||
|
||||
it('renders custom submit text', () => {
|
||||
render(<SubmitButton submitText="Submit" />);
|
||||
expect(screen.getByText('Submit')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders children over submitText', () => {
|
||||
render(<SubmitButton submitText="Submit">Custom</SubmitButton>);
|
||||
expect(screen.getByText('Custom')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows loading text when loading', () => {
|
||||
render(<SubmitButton isLoading />);
|
||||
expect(screen.getByText('Saving...')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
165
frontend/src/components/ui/__tests__/Card.test.tsx
Normal file
165
frontend/src/components/ui/__tests__/Card.test.tsx
Normal file
@@ -0,0 +1,165 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { Card, CardHeader, CardBody, CardFooter } from '../Card';
|
||||
|
||||
describe('Card', () => {
|
||||
it('renders children', () => {
|
||||
render(<Card>Card content</Card>);
|
||||
expect(screen.getByText('Card content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies base card styling', () => {
|
||||
const { container } = render(<Card>Content</Card>);
|
||||
expect(container.firstChild).toHaveClass('bg-white', 'rounded-lg', 'shadow-sm');
|
||||
});
|
||||
|
||||
it('applies bordered style by default', () => {
|
||||
const { container } = render(<Card>Content</Card>);
|
||||
expect(container.firstChild).toHaveClass('border');
|
||||
});
|
||||
|
||||
it('can remove border', () => {
|
||||
const { container } = render(<Card bordered={false}>Content</Card>);
|
||||
expect(container.firstChild).not.toHaveClass('border');
|
||||
});
|
||||
|
||||
it('applies medium padding by default', () => {
|
||||
const { container } = render(<Card>Content</Card>);
|
||||
expect(container.firstChild).toHaveClass('p-4');
|
||||
});
|
||||
|
||||
it('applies no padding', () => {
|
||||
const { container } = render(<Card padding="none">Content</Card>);
|
||||
expect(container.firstChild).not.toHaveClass('p-3', 'p-4', 'p-6');
|
||||
});
|
||||
|
||||
it('applies small padding', () => {
|
||||
const { container } = render(<Card padding="sm">Content</Card>);
|
||||
expect(container.firstChild).toHaveClass('p-3');
|
||||
});
|
||||
|
||||
it('applies large padding', () => {
|
||||
const { container } = render(<Card padding="lg">Content</Card>);
|
||||
expect(container.firstChild).toHaveClass('p-6');
|
||||
});
|
||||
|
||||
it('applies hoverable styling when hoverable', () => {
|
||||
const { container } = render(<Card hoverable>Content</Card>);
|
||||
expect(container.firstChild).toHaveClass('hover:shadow-md', 'cursor-pointer');
|
||||
});
|
||||
|
||||
it('is not hoverable by default', () => {
|
||||
const { container } = render(<Card>Content</Card>);
|
||||
expect(container.firstChild).not.toHaveClass('cursor-pointer');
|
||||
});
|
||||
|
||||
it('handles click events', () => {
|
||||
const handleClick = vi.fn();
|
||||
render(<Card onClick={handleClick}>Content</Card>);
|
||||
fireEvent.click(screen.getByText('Content'));
|
||||
expect(handleClick).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('has button role when clickable', () => {
|
||||
render(<Card onClick={() => {}}>Content</Card>);
|
||||
expect(screen.getByRole('button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('has tabIndex when clickable', () => {
|
||||
render(<Card onClick={() => {}}>Content</Card>);
|
||||
expect(screen.getByRole('button')).toHaveAttribute('tabIndex', '0');
|
||||
});
|
||||
|
||||
it('does not have button role when not clickable', () => {
|
||||
render(<Card>Content</Card>);
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<Card className="custom-class">Content</Card>);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CardHeader', () => {
|
||||
it('renders children', () => {
|
||||
render(<CardHeader>Header content</CardHeader>);
|
||||
expect(screen.getByText('Header content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies header styling', () => {
|
||||
const { container } = render(<CardHeader>Header</CardHeader>);
|
||||
expect(container.firstChild).toHaveClass('flex', 'items-center', 'justify-between');
|
||||
});
|
||||
|
||||
it('applies border bottom', () => {
|
||||
const { container } = render(<CardHeader>Header</CardHeader>);
|
||||
expect(container.firstChild).toHaveClass('border-b');
|
||||
});
|
||||
|
||||
it('renders actions when provided', () => {
|
||||
render(<CardHeader actions={<button>Action</button>}>Header</CardHeader>);
|
||||
expect(screen.getByText('Action')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<CardHeader className="custom-class">Header</CardHeader>);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('applies font styling to header text', () => {
|
||||
const { container } = render(<CardHeader>Header</CardHeader>);
|
||||
const headerText = container.querySelector('.font-semibold');
|
||||
expect(headerText).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('CardBody', () => {
|
||||
it('renders children', () => {
|
||||
render(<CardBody>Body content</CardBody>);
|
||||
expect(screen.getByText('Body content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies body styling', () => {
|
||||
const { container } = render(<CardBody>Body</CardBody>);
|
||||
expect(container.firstChild).toHaveClass('py-4');
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<CardBody className="custom-class">Body</CardBody>);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CardFooter', () => {
|
||||
it('renders children', () => {
|
||||
render(<CardFooter>Footer content</CardFooter>);
|
||||
expect(screen.getByText('Footer content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies footer styling', () => {
|
||||
const { container } = render(<CardFooter>Footer</CardFooter>);
|
||||
expect(container.firstChild).toHaveClass('pt-4', 'border-t');
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<CardFooter className="custom-class">Footer</CardFooter>);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Card composition', () => {
|
||||
it('renders complete card with all parts', () => {
|
||||
render(
|
||||
<Card>
|
||||
<CardHeader actions={<button>Edit</button>}>Title</CardHeader>
|
||||
<CardBody>Main content here</CardBody>
|
||||
<CardFooter>Footer content</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
expect(screen.getByText('Title')).toBeInTheDocument();
|
||||
expect(screen.getByText('Edit')).toBeInTheDocument();
|
||||
expect(screen.getByText('Main content here')).toBeInTheDocument();
|
||||
expect(screen.getByText('Footer content')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
310
frontend/src/components/ui/__tests__/CurrencyInput.test.tsx
Normal file
310
frontend/src/components/ui/__tests__/CurrencyInput.test.tsx
Normal file
@@ -0,0 +1,310 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import CurrencyInput from '../CurrencyInput';
|
||||
|
||||
describe('CurrencyInput', () => {
|
||||
const defaultProps = {
|
||||
value: 0,
|
||||
onChange: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Rendering', () => {
|
||||
it('renders an input element', () => {
|
||||
render(<CurrencyInput {...defaultProps} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders with default placeholder', () => {
|
||||
render(<CurrencyInput {...defaultProps} />);
|
||||
const input = screen.getByPlaceholderText('$0.00');
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders with custom placeholder', () => {
|
||||
render(<CurrencyInput {...defaultProps} placeholder="Enter amount" />);
|
||||
const input = screen.getByPlaceholderText('Enter amount');
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(<CurrencyInput {...defaultProps} className="custom-class" />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('displays formatted value for non-zero cents', () => {
|
||||
render(<CurrencyInput {...defaultProps} value={1234} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('$12.34');
|
||||
});
|
||||
|
||||
it('displays empty for zero value', () => {
|
||||
render(<CurrencyInput {...defaultProps} value={0} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('');
|
||||
});
|
||||
|
||||
it('can be disabled', () => {
|
||||
render(<CurrencyInput {...defaultProps} disabled />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toBeDisabled();
|
||||
});
|
||||
|
||||
it('can be required', () => {
|
||||
render(<CurrencyInput {...defaultProps} required />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toBeRequired();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Value Formatting', () => {
|
||||
it('formats 5 cents as $0.05', () => {
|
||||
render(<CurrencyInput {...defaultProps} value={5} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('$0.05');
|
||||
});
|
||||
|
||||
it('formats 50 cents as $0.50', () => {
|
||||
render(<CurrencyInput {...defaultProps} value={50} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('$0.50');
|
||||
});
|
||||
|
||||
it('formats 500 cents as $5.00', () => {
|
||||
render(<CurrencyInput {...defaultProps} value={500} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('$5.00');
|
||||
});
|
||||
|
||||
it('formats 1234 cents as $12.34', () => {
|
||||
render(<CurrencyInput {...defaultProps} value={1234} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('$12.34');
|
||||
});
|
||||
|
||||
it('formats large amounts correctly', () => {
|
||||
render(<CurrencyInput {...defaultProps} value={999999} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('$9999.99');
|
||||
});
|
||||
});
|
||||
|
||||
describe('User Input', () => {
|
||||
it('calls onChange with cents value when digits entered', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
fireEvent.change(input, { target: { value: '1234' } });
|
||||
expect(onChange).toHaveBeenCalledWith(1234);
|
||||
});
|
||||
|
||||
it('extracts only digits from input', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
fireEvent.change(input, { target: { value: '$12.34' } });
|
||||
expect(onChange).toHaveBeenCalledWith(1234);
|
||||
});
|
||||
|
||||
it('handles empty input', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} value={100} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
fireEvent.change(input, { target: { value: '' } });
|
||||
expect(onChange).toHaveBeenCalledWith(0);
|
||||
});
|
||||
|
||||
it('ignores non-digit characters', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
fireEvent.change(input, { target: { value: 'abc123xyz456' } });
|
||||
expect(onChange).toHaveBeenCalledWith(123456);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Min/Max Constraints', () => {
|
||||
it('enforces max value on input', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} max={1000} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
fireEvent.change(input, { target: { value: '5000' } });
|
||||
expect(onChange).toHaveBeenCalledWith(1000);
|
||||
});
|
||||
|
||||
it('enforces min value on blur', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} min={100} value={50} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
fireEvent.blur(input);
|
||||
expect(onChange).toHaveBeenCalledWith(100);
|
||||
});
|
||||
|
||||
it('does not enforce min on blur when value is zero', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} min={100} value={0} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
fireEvent.blur(input);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Focus Behavior', () => {
|
||||
it('selects all text on focus', async () => {
|
||||
vi.useFakeTimers();
|
||||
render(<CurrencyInput {...defaultProps} value={1234} />);
|
||||
const input = screen.getByRole('textbox') as HTMLInputElement;
|
||||
|
||||
const selectSpy = vi.spyOn(input, 'select');
|
||||
fireEvent.focus(input);
|
||||
|
||||
vi.runAllTimers();
|
||||
expect(selectSpy).toHaveBeenCalled();
|
||||
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Paste Handling', () => {
|
||||
it('handles paste with digits', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
const pasteEvent = {
|
||||
preventDefault: vi.fn(),
|
||||
clipboardData: {
|
||||
getData: () => '1234',
|
||||
},
|
||||
};
|
||||
|
||||
fireEvent.paste(input, pasteEvent);
|
||||
expect(onChange).toHaveBeenCalledWith(1234);
|
||||
});
|
||||
|
||||
it('extracts digits from pasted text', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
const pasteEvent = {
|
||||
preventDefault: vi.fn(),
|
||||
clipboardData: {
|
||||
getData: () => '$12.34',
|
||||
},
|
||||
};
|
||||
|
||||
fireEvent.paste(input, pasteEvent);
|
||||
expect(onChange).toHaveBeenCalledWith(1234);
|
||||
});
|
||||
|
||||
it('enforces max on paste', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} max={500} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
const pasteEvent = {
|
||||
preventDefault: vi.fn(),
|
||||
clipboardData: {
|
||||
getData: () => '1000',
|
||||
},
|
||||
};
|
||||
|
||||
fireEvent.paste(input, pasteEvent);
|
||||
expect(onChange).toHaveBeenCalledWith(500);
|
||||
});
|
||||
|
||||
it('ignores empty paste', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
const pasteEvent = {
|
||||
preventDefault: vi.fn(),
|
||||
clipboardData: {
|
||||
getData: () => '',
|
||||
},
|
||||
};
|
||||
|
||||
fireEvent.paste(input, pasteEvent);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Keyboard Handling', () => {
|
||||
it('allows digit keys (can type digits)', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<CurrencyInput {...defaultProps} onChange={onChange} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
// Type a digit
|
||||
fireEvent.change(input, { target: { value: '5' } });
|
||||
expect(onChange).toHaveBeenCalledWith(5);
|
||||
});
|
||||
|
||||
it('handles navigation keys (component accepts them)', () => {
|
||||
render(<CurrencyInput {...defaultProps} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
const navigationKeys = ['Backspace', 'Delete', 'Tab', 'ArrowLeft', 'ArrowRight'];
|
||||
|
||||
navigationKeys.forEach((key) => {
|
||||
// These should not throw or cause issues
|
||||
fireEvent.keyDown(input, { key });
|
||||
});
|
||||
|
||||
// If we got here without errors, navigation keys are handled
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('allows Ctrl+A for select all', () => {
|
||||
render(<CurrencyInput {...defaultProps} value={1234} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
// Ctrl+A should not cause issues
|
||||
fireEvent.keyDown(input, { key: 'a', ctrlKey: true });
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('allows Cmd+C for copy', () => {
|
||||
render(<CurrencyInput {...defaultProps} value={1234} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
// Cmd+C should not cause issues
|
||||
fireEvent.keyDown(input, { key: 'c', metaKey: true });
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Input Attributes', () => {
|
||||
it('has numeric input mode', () => {
|
||||
render(<CurrencyInput {...defaultProps} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveAttribute('inputMode', 'numeric');
|
||||
});
|
||||
|
||||
it('disables autocomplete', () => {
|
||||
render(<CurrencyInput {...defaultProps} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveAttribute('autoComplete', 'off');
|
||||
});
|
||||
|
||||
it('disables spell check', () => {
|
||||
render(<CurrencyInput {...defaultProps} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveAttribute('spellCheck', 'false');
|
||||
});
|
||||
});
|
||||
});
|
||||
81
frontend/src/components/ui/__tests__/EmptyState.test.tsx
Normal file
81
frontend/src/components/ui/__tests__/EmptyState.test.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { EmptyState } from '../EmptyState';
|
||||
|
||||
describe('EmptyState', () => {
|
||||
it('renders title', () => {
|
||||
render(<EmptyState title="No items found" />);
|
||||
expect(screen.getByText('No items found')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders description when provided', () => {
|
||||
render(<EmptyState title="No items" description="Try adding some items" />);
|
||||
expect(screen.getByText('Try adding some items')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render description when not provided', () => {
|
||||
const { container } = render(<EmptyState title="No items" />);
|
||||
const descriptions = container.querySelectorAll('p');
|
||||
expect(descriptions.length).toBe(0);
|
||||
});
|
||||
|
||||
it('renders default icon when not provided', () => {
|
||||
const { container } = render(<EmptyState title="No items" />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders custom icon when provided', () => {
|
||||
render(<EmptyState title="No items" icon={<span data-testid="custom-icon">📭</span>} />);
|
||||
expect(screen.getByTestId('custom-icon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders action when provided', () => {
|
||||
render(<EmptyState title="No items" action={<button>Add item</button>} />);
|
||||
expect(screen.getByText('Add item')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render action when not provided', () => {
|
||||
render(<EmptyState title="No items" />);
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies center text alignment', () => {
|
||||
const { container } = render(<EmptyState title="No items" />);
|
||||
expect(container.firstChild).toHaveClass('text-center');
|
||||
});
|
||||
|
||||
it('applies padding', () => {
|
||||
const { container } = render(<EmptyState title="No items" />);
|
||||
expect(container.firstChild).toHaveClass('py-12', 'px-4');
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<EmptyState title="No items" className="custom-class" />);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('renders title with proper styling', () => {
|
||||
render(<EmptyState title="No items" />);
|
||||
const title = screen.getByText('No items');
|
||||
expect(title).toHaveClass('text-lg', 'font-medium');
|
||||
});
|
||||
|
||||
it('renders description with proper styling', () => {
|
||||
render(<EmptyState title="No items" description="Add some items" />);
|
||||
const description = screen.getByText('Add some items');
|
||||
expect(description).toHaveClass('text-sm', 'text-gray-500');
|
||||
});
|
||||
|
||||
it('centers the icon', () => {
|
||||
const { container } = render(<EmptyState title="No items" />);
|
||||
const iconContainer = container.querySelector('.flex.justify-center');
|
||||
expect(iconContainer).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('constrains description width', () => {
|
||||
render(<EmptyState title="No items" description="Long description text" />);
|
||||
const description = screen.getByText('Long description text');
|
||||
expect(description).toHaveClass('max-w-sm', 'mx-auto');
|
||||
});
|
||||
});
|
||||
241
frontend/src/components/ui/__tests__/FormCurrencyInput.test.tsx
Normal file
241
frontend/src/components/ui/__tests__/FormCurrencyInput.test.tsx
Normal file
@@ -0,0 +1,241 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import FormCurrencyInput from '../FormCurrencyInput';
|
||||
|
||||
describe('FormCurrencyInput', () => {
|
||||
const defaultProps = {
|
||||
value: 0,
|
||||
onChange: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Label Rendering', () => {
|
||||
it('renders without label when not provided', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} />);
|
||||
expect(screen.queryByRole('label')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders label when provided', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} label="Price" />);
|
||||
expect(screen.getByText('Price')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows required indicator when required', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} label="Price" required />);
|
||||
expect(screen.getByText('*')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show required indicator when not required', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} label="Price" />);
|
||||
expect(screen.queryByText('*')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('does not show error when not provided', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} />);
|
||||
expect(screen.queryByText(/error/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error message when provided', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} error="Price is required" />);
|
||||
expect(screen.getByText('Price is required')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies error styling to input', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} error="Error" />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveClass('border-red-500');
|
||||
});
|
||||
|
||||
it('error has correct text color', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} error="Price is required" />);
|
||||
const error = screen.getByText('Price is required');
|
||||
expect(error).toHaveClass('text-red-600');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Hint Rendering', () => {
|
||||
it('does not show hint when not provided', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} />);
|
||||
expect(screen.queryByText(/hint/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows hint when provided', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} hint="Enter price in dollars" />);
|
||||
expect(screen.getByText('Enter price in dollars')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides hint when error is shown', () => {
|
||||
render(
|
||||
<FormCurrencyInput
|
||||
{...defaultProps}
|
||||
hint="Enter price"
|
||||
error="Price required"
|
||||
/>
|
||||
);
|
||||
expect(screen.queryByText('Enter price')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Price required')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hint has correct text color', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} hint="Helpful text" />);
|
||||
const hint = screen.getByText('Helpful text');
|
||||
expect(hint).toHaveClass('text-gray-500');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Input Behavior', () => {
|
||||
it('renders input with default placeholder', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} />);
|
||||
const input = screen.getByPlaceholderText('$0.00');
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders input with custom placeholder', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} placeholder="Enter amount" />);
|
||||
const input = screen.getByPlaceholderText('Enter amount');
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays formatted value', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} value={1000} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveValue('$10.00');
|
||||
});
|
||||
|
||||
it('calls onChange when value changes', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<FormCurrencyInput {...defaultProps} onChange={onChange} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
fireEvent.change(input, { target: { value: '500' } });
|
||||
expect(onChange).toHaveBeenCalledWith(500);
|
||||
});
|
||||
|
||||
it('can be disabled', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} disabled />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toBeDisabled();
|
||||
});
|
||||
|
||||
it('applies disabled styling', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} disabled />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveClass('cursor-not-allowed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Min/Max Props', () => {
|
||||
it('passes min prop to CurrencyInput', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<FormCurrencyInput {...defaultProps} onChange={onChange} min={100} value={50} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
fireEvent.blur(input);
|
||||
expect(onChange).toHaveBeenCalledWith(100);
|
||||
});
|
||||
|
||||
it('passes max prop to CurrencyInput', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<FormCurrencyInput {...defaultProps} onChange={onChange} max={1000} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
fireEvent.change(input, { target: { value: '5000' } });
|
||||
expect(onChange).toHaveBeenCalledWith(1000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Styling', () => {
|
||||
it('applies containerClassName to wrapper', () => {
|
||||
const { container } = render(
|
||||
<FormCurrencyInput {...defaultProps} containerClassName="my-container" />
|
||||
);
|
||||
expect(container.firstChild).toHaveClass('my-container');
|
||||
});
|
||||
|
||||
it('applies className to input', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} className="my-input" />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveClass('my-input');
|
||||
});
|
||||
|
||||
it('applies base input classes', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveClass('w-full', 'px-3', 'py-2', 'border', 'rounded-lg');
|
||||
});
|
||||
|
||||
it('applies normal border when no error', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveClass('border-gray-300');
|
||||
});
|
||||
|
||||
it('applies error border when error provided', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} error="Error" />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveClass('border-red-500');
|
||||
expect(input).not.toHaveClass('border-gray-300');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accessibility', () => {
|
||||
it('associates label with input', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} label="Price" />);
|
||||
const label = screen.getByText('Price');
|
||||
expect(label.tagName).toBe('LABEL');
|
||||
});
|
||||
|
||||
it('marks input as required when required prop is true', () => {
|
||||
render(<FormCurrencyInput {...defaultProps} required />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toBeRequired();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Integration', () => {
|
||||
it('full form flow works correctly', () => {
|
||||
const onChange = vi.fn();
|
||||
render(
|
||||
<FormCurrencyInput
|
||||
label="Service Price"
|
||||
hint="Enter the price for this service"
|
||||
value={0}
|
||||
onChange={onChange}
|
||||
required
|
||||
min={100}
|
||||
max={100000}
|
||||
/>
|
||||
);
|
||||
|
||||
// Check label and hint render
|
||||
expect(screen.getByText('Service Price')).toBeInTheDocument();
|
||||
expect(screen.getByText('Enter the price for this service')).toBeInTheDocument();
|
||||
expect(screen.getByText('*')).toBeInTheDocument();
|
||||
|
||||
// Enter a value
|
||||
const input = screen.getByRole('textbox');
|
||||
fireEvent.change(input, { target: { value: '2500' } });
|
||||
expect(onChange).toHaveBeenCalledWith(2500);
|
||||
});
|
||||
|
||||
it('shows error state correctly', () => {
|
||||
render(
|
||||
<FormCurrencyInput
|
||||
label="Price"
|
||||
error="Price must be greater than $1.00"
|
||||
value={50}
|
||||
onChange={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Price must be greater than $1.00')).toBeInTheDocument();
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveClass('border-red-500');
|
||||
});
|
||||
});
|
||||
});
|
||||
136
frontend/src/components/ui/__tests__/FormInput.test.tsx
Normal file
136
frontend/src/components/ui/__tests__/FormInput.test.tsx
Normal file
@@ -0,0 +1,136 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { FormInput } from '../FormInput';
|
||||
|
||||
describe('FormInput', () => {
|
||||
it('renders input element', () => {
|
||||
render(<FormInput />);
|
||||
expect(screen.getByRole('textbox')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders label when provided', () => {
|
||||
render(<FormInput label="Username" />);
|
||||
expect(screen.getByText('Username')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows required indicator when required', () => {
|
||||
render(<FormInput label="Email" required />);
|
||||
expect(screen.getByText('*')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays error message', () => {
|
||||
render(<FormInput error="This field is required" />);
|
||||
expect(screen.getByText('This field is required')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays hint when provided', () => {
|
||||
render(<FormInput hint="Enter your username" />);
|
||||
expect(screen.getByText('Enter your username')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides hint when error is shown', () => {
|
||||
render(<FormInput hint="Enter your username" error="Required" />);
|
||||
expect(screen.queryByText('Enter your username')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Required')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies error styling when error present', () => {
|
||||
render(<FormInput error="Invalid" />);
|
||||
expect(screen.getByRole('textbox')).toHaveClass('border-red-500');
|
||||
});
|
||||
|
||||
it('applies disabled styling', () => {
|
||||
render(<FormInput disabled />);
|
||||
expect(screen.getByRole('textbox')).toBeDisabled();
|
||||
expect(screen.getByRole('textbox')).toHaveClass('cursor-not-allowed');
|
||||
});
|
||||
|
||||
it('applies small size classes', () => {
|
||||
render(<FormInput inputSize="sm" />);
|
||||
expect(screen.getByRole('textbox')).toHaveClass('py-1');
|
||||
});
|
||||
|
||||
it('applies medium size classes by default', () => {
|
||||
render(<FormInput />);
|
||||
expect(screen.getByRole('textbox')).toHaveClass('py-2');
|
||||
});
|
||||
|
||||
it('applies large size classes', () => {
|
||||
render(<FormInput inputSize="lg" />);
|
||||
expect(screen.getByRole('textbox')).toHaveClass('py-3');
|
||||
});
|
||||
|
||||
it('applies full width by default', () => {
|
||||
render(<FormInput />);
|
||||
expect(screen.getByRole('textbox')).toHaveClass('w-full');
|
||||
});
|
||||
|
||||
it('can disable full width', () => {
|
||||
render(<FormInput fullWidth={false} />);
|
||||
expect(screen.getByRole('textbox')).not.toHaveClass('w-full');
|
||||
});
|
||||
|
||||
it('renders left icon', () => {
|
||||
render(<FormInput leftIcon={<span data-testid="left-icon">L</span>} />);
|
||||
expect(screen.getByTestId('left-icon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders right icon', () => {
|
||||
render(<FormInput rightIcon={<span data-testid="right-icon">R</span>} />);
|
||||
expect(screen.getByTestId('right-icon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(<FormInput className="custom-class" />);
|
||||
expect(screen.getByRole('textbox')).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('applies custom containerClassName', () => {
|
||||
const { container } = render(<FormInput containerClassName="container-class" />);
|
||||
expect(container.firstChild).toHaveClass('container-class');
|
||||
});
|
||||
|
||||
it('handles value changes', () => {
|
||||
const handleChange = vi.fn();
|
||||
render(<FormInput onChange={handleChange} />);
|
||||
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'test' } });
|
||||
expect(handleChange).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses provided id', () => {
|
||||
render(<FormInput id="custom-id" label="Label" />);
|
||||
expect(screen.getByRole('textbox')).toHaveAttribute('id', 'custom-id');
|
||||
});
|
||||
|
||||
it('uses name as id fallback', () => {
|
||||
render(<FormInput name="username" label="Label" />);
|
||||
expect(screen.getByRole('textbox')).toHaveAttribute('id', 'username');
|
||||
});
|
||||
|
||||
it('generates random id when none provided', () => {
|
||||
render(<FormInput label="Label" />);
|
||||
expect(screen.getByRole('textbox')).toHaveAttribute('id');
|
||||
});
|
||||
|
||||
it('links label to input', () => {
|
||||
render(<FormInput id="my-input" label="My Label" />);
|
||||
const input = screen.getByRole('textbox');
|
||||
const label = screen.getByText('My Label');
|
||||
expect(label).toHaveAttribute('for', 'my-input');
|
||||
expect(input).toHaveAttribute('id', 'my-input');
|
||||
});
|
||||
|
||||
it('forwards ref to input element', () => {
|
||||
const ref = { current: null as HTMLInputElement | null };
|
||||
render(<FormInput ref={ref} />);
|
||||
expect(ref.current).toBeInstanceOf(HTMLInputElement);
|
||||
});
|
||||
|
||||
it('passes through other input props', () => {
|
||||
render(<FormInput placeholder="Enter text" type="email" maxLength={50} />);
|
||||
const input = screen.getByRole('textbox');
|
||||
expect(input).toHaveAttribute('placeholder', 'Enter text');
|
||||
expect(input).toHaveAttribute('type', 'email');
|
||||
expect(input).toHaveAttribute('maxLength', '50');
|
||||
});
|
||||
});
|
||||
149
frontend/src/components/ui/__tests__/FormSelect.test.tsx
Normal file
149
frontend/src/components/ui/__tests__/FormSelect.test.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { FormSelect } from '../FormSelect';
|
||||
|
||||
const options = [
|
||||
{ value: 'option1', label: 'Option 1' },
|
||||
{ value: 'option2', label: 'Option 2' },
|
||||
{ value: 'option3', label: 'Option 3', disabled: true },
|
||||
];
|
||||
|
||||
describe('FormSelect', () => {
|
||||
it('renders select element', () => {
|
||||
render(<FormSelect options={options} />);
|
||||
expect(screen.getByRole('combobox')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders options', () => {
|
||||
render(<FormSelect options={options} />);
|
||||
expect(screen.getByText('Option 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Option 2')).toBeInTheDocument();
|
||||
expect(screen.getByText('Option 3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders label when provided', () => {
|
||||
render(<FormSelect label="Select Option" options={options} />);
|
||||
expect(screen.getByText('Select Option')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows required indicator when required', () => {
|
||||
render(<FormSelect label="Category" options={options} required />);
|
||||
expect(screen.getByText('*')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays placeholder option', () => {
|
||||
render(<FormSelect options={options} placeholder="Choose one" />);
|
||||
expect(screen.getByText('Choose one')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('disables placeholder option', () => {
|
||||
render(<FormSelect options={options} placeholder="Choose one" />);
|
||||
const placeholder = screen.getByText('Choose one');
|
||||
expect(placeholder).toHaveAttribute('disabled');
|
||||
});
|
||||
|
||||
it('displays error message', () => {
|
||||
render(<FormSelect options={options} error="Selection required" />);
|
||||
expect(screen.getByText('Selection required')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays hint when provided', () => {
|
||||
render(<FormSelect options={options} hint="Select your preference" />);
|
||||
expect(screen.getByText('Select your preference')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides hint when error is shown', () => {
|
||||
render(<FormSelect options={options} hint="Select option" error="Required" />);
|
||||
expect(screen.queryByText('Select option')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Required')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies error styling when error present', () => {
|
||||
render(<FormSelect options={options} error="Invalid" />);
|
||||
expect(screen.getByRole('combobox')).toHaveClass('border-red-500');
|
||||
});
|
||||
|
||||
it('applies disabled styling', () => {
|
||||
render(<FormSelect options={options} disabled />);
|
||||
expect(screen.getByRole('combobox')).toBeDisabled();
|
||||
expect(screen.getByRole('combobox')).toHaveClass('cursor-not-allowed');
|
||||
});
|
||||
|
||||
it('disables individual options', () => {
|
||||
render(<FormSelect options={options} />);
|
||||
const option3 = screen.getByText('Option 3');
|
||||
expect(option3).toHaveAttribute('disabled');
|
||||
});
|
||||
|
||||
it('applies small size classes', () => {
|
||||
render(<FormSelect options={options} selectSize="sm" />);
|
||||
expect(screen.getByRole('combobox')).toHaveClass('py-1');
|
||||
});
|
||||
|
||||
it('applies medium size classes by default', () => {
|
||||
render(<FormSelect options={options} />);
|
||||
expect(screen.getByRole('combobox')).toHaveClass('py-2');
|
||||
});
|
||||
|
||||
it('applies large size classes', () => {
|
||||
render(<FormSelect options={options} selectSize="lg" />);
|
||||
expect(screen.getByRole('combobox')).toHaveClass('py-3');
|
||||
});
|
||||
|
||||
it('applies full width by default', () => {
|
||||
render(<FormSelect options={options} />);
|
||||
expect(screen.getByRole('combobox')).toHaveClass('w-full');
|
||||
});
|
||||
|
||||
it('can disable full width', () => {
|
||||
render(<FormSelect options={options} fullWidth={false} />);
|
||||
expect(screen.getByRole('combobox')).not.toHaveClass('w-full');
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(<FormSelect options={options} className="custom-class" />);
|
||||
expect(screen.getByRole('combobox')).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('applies custom containerClassName', () => {
|
||||
const { container } = render(<FormSelect options={options} containerClassName="container-class" />);
|
||||
expect(container.firstChild).toHaveClass('container-class');
|
||||
});
|
||||
|
||||
it('handles value changes', () => {
|
||||
const handleChange = vi.fn();
|
||||
render(<FormSelect options={options} onChange={handleChange} />);
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'option2' } });
|
||||
expect(handleChange).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses provided id', () => {
|
||||
render(<FormSelect options={options} id="custom-id" label="Label" />);
|
||||
expect(screen.getByRole('combobox')).toHaveAttribute('id', 'custom-id');
|
||||
});
|
||||
|
||||
it('uses name as id fallback', () => {
|
||||
render(<FormSelect options={options} name="category" label="Label" />);
|
||||
expect(screen.getByRole('combobox')).toHaveAttribute('id', 'category');
|
||||
});
|
||||
|
||||
it('links label to select', () => {
|
||||
render(<FormSelect options={options} id="my-select" label="My Label" />);
|
||||
const select = screen.getByRole('combobox');
|
||||
const label = screen.getByText('My Label');
|
||||
expect(label).toHaveAttribute('for', 'my-select');
|
||||
expect(select).toHaveAttribute('id', 'my-select');
|
||||
});
|
||||
|
||||
it('forwards ref to select element', () => {
|
||||
const ref = { current: null as HTMLSelectElement | null };
|
||||
render(<FormSelect options={options} ref={ref} />);
|
||||
expect(ref.current).toBeInstanceOf(HTMLSelectElement);
|
||||
});
|
||||
|
||||
it('renders dropdown arrow icon', () => {
|
||||
const { container } = render(<FormSelect options={options} />);
|
||||
const svg = container.querySelector('svg');
|
||||
expect(svg).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
120
frontend/src/components/ui/__tests__/FormTextarea.test.tsx
Normal file
120
frontend/src/components/ui/__tests__/FormTextarea.test.tsx
Normal file
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { FormTextarea } from '../FormTextarea';
|
||||
|
||||
describe('FormTextarea', () => {
|
||||
it('renders textarea element', () => {
|
||||
render(<FormTextarea />);
|
||||
expect(screen.getByRole('textbox')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders label when provided', () => {
|
||||
render(<FormTextarea label="Description" />);
|
||||
expect(screen.getByText('Description')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows required indicator when required', () => {
|
||||
render(<FormTextarea label="Comments" required />);
|
||||
expect(screen.getByText('*')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays error message', () => {
|
||||
render(<FormTextarea error="This field is required" />);
|
||||
expect(screen.getByText('This field is required')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays hint when provided', () => {
|
||||
render(<FormTextarea hint="Max 500 characters" />);
|
||||
expect(screen.getByText('Max 500 characters')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides hint when error is shown', () => {
|
||||
render(<FormTextarea hint="Enter description" error="Required" />);
|
||||
expect(screen.queryByText('Enter description')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Required')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies error styling when error present', () => {
|
||||
render(<FormTextarea error="Invalid" />);
|
||||
expect(screen.getByRole('textbox')).toHaveClass('border-red-500');
|
||||
});
|
||||
|
||||
it('applies disabled styling', () => {
|
||||
render(<FormTextarea disabled />);
|
||||
expect(screen.getByRole('textbox')).toBeDisabled();
|
||||
expect(screen.getByRole('textbox')).toHaveClass('cursor-not-allowed');
|
||||
});
|
||||
|
||||
it('applies full width by default', () => {
|
||||
render(<FormTextarea />);
|
||||
expect(screen.getByRole('textbox')).toHaveClass('w-full');
|
||||
});
|
||||
|
||||
it('can disable full width', () => {
|
||||
render(<FormTextarea fullWidth={false} />);
|
||||
expect(screen.getByRole('textbox')).not.toHaveClass('w-full');
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(<FormTextarea className="custom-class" />);
|
||||
expect(screen.getByRole('textbox')).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('applies custom containerClassName', () => {
|
||||
const { container } = render(<FormTextarea containerClassName="container-class" />);
|
||||
expect(container.firstChild).toHaveClass('container-class');
|
||||
});
|
||||
|
||||
it('handles value changes', () => {
|
||||
const handleChange = vi.fn();
|
||||
render(<FormTextarea onChange={handleChange} />);
|
||||
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'test content' } });
|
||||
expect(handleChange).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses provided id', () => {
|
||||
render(<FormTextarea id="custom-id" label="Label" />);
|
||||
expect(screen.getByRole('textbox')).toHaveAttribute('id', 'custom-id');
|
||||
});
|
||||
|
||||
it('uses name as id fallback', () => {
|
||||
render(<FormTextarea name="description" label="Label" />);
|
||||
expect(screen.getByRole('textbox')).toHaveAttribute('id', 'description');
|
||||
});
|
||||
|
||||
it('links label to textarea', () => {
|
||||
render(<FormTextarea id="my-textarea" label="My Label" />);
|
||||
const textarea = screen.getByRole('textbox');
|
||||
const label = screen.getByText('My Label');
|
||||
expect(label).toHaveAttribute('for', 'my-textarea');
|
||||
expect(textarea).toHaveAttribute('id', 'my-textarea');
|
||||
});
|
||||
|
||||
it('forwards ref to textarea element', () => {
|
||||
const ref = { current: null as HTMLTextAreaElement | null };
|
||||
render(<FormTextarea ref={ref} />);
|
||||
expect(ref.current).toBeInstanceOf(HTMLTextAreaElement);
|
||||
});
|
||||
|
||||
it('shows character count when enabled', () => {
|
||||
render(<FormTextarea showCharCount value="Hello" />);
|
||||
expect(screen.getByText('5')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows character count with max chars', () => {
|
||||
render(<FormTextarea showCharCount maxChars={100} value="Hello" />);
|
||||
expect(screen.getByText('5/100')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies warning style when over max chars', () => {
|
||||
render(<FormTextarea showCharCount maxChars={5} value="Hello World" />);
|
||||
expect(screen.getByText('11/5')).toHaveClass('text-red-500');
|
||||
});
|
||||
|
||||
it('passes through other textarea props', () => {
|
||||
render(<FormTextarea placeholder="Enter text" rows={5} />);
|
||||
const textarea = screen.getByRole('textbox');
|
||||
expect(textarea).toHaveAttribute('placeholder', 'Enter text');
|
||||
expect(textarea).toHaveAttribute('rows', '5');
|
||||
});
|
||||
});
|
||||
147
frontend/src/components/ui/__tests__/LoadingSpinner.test.tsx
Normal file
147
frontend/src/components/ui/__tests__/LoadingSpinner.test.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { LoadingSpinner, PageLoading, InlineLoading } from '../LoadingSpinner';
|
||||
|
||||
describe('LoadingSpinner', () => {
|
||||
it('renders spinner element', () => {
|
||||
const { container } = render(<LoadingSpinner />);
|
||||
expect(container.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies default size (md)', () => {
|
||||
const { container } = render(<LoadingSpinner />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('h-6', 'w-6');
|
||||
});
|
||||
|
||||
it('applies xs size', () => {
|
||||
const { container } = render(<LoadingSpinner size="xs" />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('h-3', 'w-3');
|
||||
});
|
||||
|
||||
it('applies sm size', () => {
|
||||
const { container } = render(<LoadingSpinner size="sm" />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('h-4', 'w-4');
|
||||
});
|
||||
|
||||
it('applies lg size', () => {
|
||||
const { container } = render(<LoadingSpinner size="lg" />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('h-8', 'w-8');
|
||||
});
|
||||
|
||||
it('applies xl size', () => {
|
||||
const { container } = render(<LoadingSpinner size="xl" />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('h-12', 'w-12');
|
||||
});
|
||||
|
||||
it('applies default color', () => {
|
||||
const { container } = render(<LoadingSpinner />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('text-gray-500');
|
||||
});
|
||||
|
||||
it('applies white color', () => {
|
||||
const { container } = render(<LoadingSpinner color="white" />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('text-white');
|
||||
});
|
||||
|
||||
it('applies brand color', () => {
|
||||
const { container } = render(<LoadingSpinner color="brand" />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('text-brand-600');
|
||||
});
|
||||
|
||||
it('applies blue color', () => {
|
||||
const { container } = render(<LoadingSpinner color="blue" />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('text-blue-600');
|
||||
});
|
||||
|
||||
it('renders label when provided', () => {
|
||||
render(<LoadingSpinner label="Loading data..." />);
|
||||
expect(screen.getByText('Loading data...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render label when not provided', () => {
|
||||
const { container } = render(<LoadingSpinner />);
|
||||
const spans = container.querySelectorAll('span');
|
||||
expect(spans.length).toBe(0);
|
||||
});
|
||||
|
||||
it('centers spinner when centered prop is true', () => {
|
||||
const { container } = render(<LoadingSpinner centered />);
|
||||
expect(container.firstChild).toHaveClass('flex', 'items-center', 'justify-center');
|
||||
});
|
||||
|
||||
it('does not center spinner by default', () => {
|
||||
const { container } = render(<LoadingSpinner />);
|
||||
expect(container.firstChild).not.toHaveClass('py-12');
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<LoadingSpinner className="custom-class" />);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PageLoading', () => {
|
||||
it('renders with default loading text', () => {
|
||||
render(<PageLoading />);
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders with custom label', () => {
|
||||
render(<PageLoading label="Fetching data..." />);
|
||||
expect(screen.getByText('Fetching data...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders large spinner', () => {
|
||||
const { container } = render(<PageLoading />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('h-8', 'w-8');
|
||||
});
|
||||
|
||||
it('renders with brand color', () => {
|
||||
const { container } = render(<PageLoading />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('text-brand-600');
|
||||
});
|
||||
|
||||
it('is centered in container', () => {
|
||||
const { container } = render(<PageLoading />);
|
||||
expect(container.firstChild).toHaveClass('flex', 'items-center', 'justify-center');
|
||||
});
|
||||
});
|
||||
|
||||
describe('InlineLoading', () => {
|
||||
it('renders spinner', () => {
|
||||
const { container } = render(<InlineLoading />);
|
||||
expect(container.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders label when provided', () => {
|
||||
render(<InlineLoading label="Saving..." />);
|
||||
expect(screen.getByText('Saving...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render label when not provided', () => {
|
||||
render(<InlineLoading />);
|
||||
expect(screen.queryByText(/./)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders small spinner', () => {
|
||||
const { container } = render(<InlineLoading />);
|
||||
const spinner = container.querySelector('.animate-spin');
|
||||
expect(spinner).toHaveClass('h-4', 'w-4');
|
||||
});
|
||||
|
||||
it('renders inline', () => {
|
||||
const { container } = render(<InlineLoading />);
|
||||
expect(container.firstChild).toHaveClass('inline-flex');
|
||||
});
|
||||
});
|
||||
97
frontend/src/components/ui/__tests__/Modal.test.tsx
Normal file
97
frontend/src/components/ui/__tests__/Modal.test.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { Modal } from '../Modal';
|
||||
|
||||
describe('Modal', () => {
|
||||
const defaultProps = {
|
||||
isOpen: true,
|
||||
onClose: vi.fn(),
|
||||
children: <div>Modal Content</div>,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.style.overflow = '';
|
||||
});
|
||||
|
||||
it('returns null when not open', () => {
|
||||
render(<Modal {...defaultProps} isOpen={false} />);
|
||||
expect(screen.queryByText('Modal Content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders children when open', () => {
|
||||
render(<Modal {...defaultProps} />);
|
||||
expect(screen.getByText('Modal Content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders title when provided', () => {
|
||||
render(<Modal {...defaultProps} title="Modal Title" />);
|
||||
expect(screen.getByText('Modal Title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders footer when provided', () => {
|
||||
render(<Modal {...defaultProps} footer={<button>Save</button>} />);
|
||||
expect(screen.getByText('Save')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows close button by default', () => {
|
||||
render(<Modal {...defaultProps} title="Title" />);
|
||||
expect(screen.getByLabelText('Close modal')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides close button when showCloseButton is false', () => {
|
||||
render(<Modal {...defaultProps} showCloseButton={false} />);
|
||||
expect(screen.queryByLabelText('Close modal')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onClose when close button clicked', () => {
|
||||
render(<Modal {...defaultProps} title="Title" />);
|
||||
fireEvent.click(screen.getByLabelText('Close modal'));
|
||||
expect(defaultProps.onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls onClose when overlay clicked', () => {
|
||||
render(<Modal {...defaultProps} />);
|
||||
// Click on backdrop
|
||||
const backdrop = document.querySelector('.backdrop-blur-sm');
|
||||
if (backdrop) {
|
||||
fireEvent.click(backdrop);
|
||||
expect(defaultProps.onClose).toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not close when content clicked', () => {
|
||||
render(<Modal {...defaultProps} />);
|
||||
fireEvent.click(screen.getByText('Modal Content'));
|
||||
expect(defaultProps.onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not close on overlay click when closeOnOverlayClick is false', () => {
|
||||
render(<Modal {...defaultProps} closeOnOverlayClick={false} />);
|
||||
const backdrop = document.querySelector('.backdrop-blur-sm');
|
||||
if (backdrop) {
|
||||
fireEvent.click(backdrop);
|
||||
expect(defaultProps.onClose).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it('applies size classes', () => {
|
||||
render(<Modal {...defaultProps} size="lg" />);
|
||||
const modalContent = document.querySelector('.max-w-lg');
|
||||
expect(modalContent).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
render(<Modal {...defaultProps} className="custom-class" />);
|
||||
const modalContent = document.querySelector('.custom-class');
|
||||
expect(modalContent).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('prevents body scroll when open', () => {
|
||||
render(<Modal {...defaultProps} />);
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
});
|
||||
});
|
||||
134
frontend/src/components/ui/__tests__/ModalFooter.test.tsx
Normal file
134
frontend/src/components/ui/__tests__/ModalFooter.test.tsx
Normal file
@@ -0,0 +1,134 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { ModalFooter } from '../ModalFooter';
|
||||
|
||||
describe('ModalFooter', () => {
|
||||
it('renders cancel button when onCancel provided', () => {
|
||||
render(<ModalFooter onCancel={() => {}} />);
|
||||
expect(screen.getByText('Cancel')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders submit button when onSubmit provided', () => {
|
||||
render(<ModalFooter onSubmit={() => {}} />);
|
||||
expect(screen.getByText('Save')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders both buttons when both handlers provided', () => {
|
||||
render(<ModalFooter onCancel={() => {}} onSubmit={() => {}} />);
|
||||
expect(screen.getByText('Cancel')).toBeInTheDocument();
|
||||
expect(screen.getByText('Save')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses custom submit text', () => {
|
||||
render(<ModalFooter onSubmit={() => {}} submitText="Create" />);
|
||||
expect(screen.getByText('Create')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses custom cancel text', () => {
|
||||
render(<ModalFooter onCancel={() => {}} cancelText="Close" />);
|
||||
expect(screen.getByText('Close')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onCancel when cancel button clicked', () => {
|
||||
const handleCancel = vi.fn();
|
||||
render(<ModalFooter onCancel={handleCancel} />);
|
||||
fireEvent.click(screen.getByText('Cancel'));
|
||||
expect(handleCancel).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls onSubmit when submit button clicked', () => {
|
||||
const handleSubmit = vi.fn();
|
||||
render(<ModalFooter onSubmit={handleSubmit} />);
|
||||
fireEvent.click(screen.getByText('Save'));
|
||||
expect(handleSubmit).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disables submit button when isDisabled is true', () => {
|
||||
render(<ModalFooter onSubmit={() => {}} isDisabled />);
|
||||
expect(screen.getByText('Save')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables buttons when isLoading is true', () => {
|
||||
render(<ModalFooter onCancel={() => {}} onSubmit={() => {}} isLoading />);
|
||||
expect(screen.getByText('Cancel')).toBeDisabled();
|
||||
expect(screen.getByText('Save')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows loading spinner when isLoading', () => {
|
||||
const { container } = render(<ModalFooter onSubmit={() => {}} isLoading />);
|
||||
expect(container.querySelector('.animate-spin')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders back button when showBackButton is true', () => {
|
||||
render(<ModalFooter onBack={() => {}} showBackButton />);
|
||||
expect(screen.getByText('Back')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses custom back text', () => {
|
||||
render(<ModalFooter onBack={() => {}} showBackButton backText="Previous" />);
|
||||
expect(screen.getByText('Previous')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onBack when back button clicked', () => {
|
||||
const handleBack = vi.fn();
|
||||
render(<ModalFooter onBack={handleBack} showBackButton />);
|
||||
fireEvent.click(screen.getByText('Back'));
|
||||
expect(handleBack).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not render back button without onBack handler', () => {
|
||||
render(<ModalFooter showBackButton />);
|
||||
expect(screen.queryByText('Back')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies primary variant by default', () => {
|
||||
render(<ModalFooter onSubmit={() => {}} />);
|
||||
expect(screen.getByText('Save')).toHaveClass('bg-blue-600');
|
||||
});
|
||||
|
||||
it('applies danger variant', () => {
|
||||
render(<ModalFooter onSubmit={() => {}} submitVariant="danger" />);
|
||||
expect(screen.getByText('Save')).toHaveClass('bg-red-600');
|
||||
});
|
||||
|
||||
it('applies success variant', () => {
|
||||
render(<ModalFooter onSubmit={() => {}} submitVariant="success" />);
|
||||
expect(screen.getByText('Save')).toHaveClass('bg-green-600');
|
||||
});
|
||||
|
||||
it('applies warning variant', () => {
|
||||
render(<ModalFooter onSubmit={() => {}} submitVariant="warning" />);
|
||||
expect(screen.getByText('Save')).toHaveClass('bg-amber-600');
|
||||
});
|
||||
|
||||
it('applies secondary variant', () => {
|
||||
render(<ModalFooter onSubmit={() => {}} submitVariant="secondary" />);
|
||||
expect(screen.getByText('Save')).toHaveClass('bg-gray-600');
|
||||
});
|
||||
|
||||
it('renders children instead of default buttons', () => {
|
||||
render(
|
||||
<ModalFooter onSubmit={() => {}} onCancel={() => {}}>
|
||||
<button>Custom Button</button>
|
||||
</ModalFooter>
|
||||
);
|
||||
expect(screen.getByText('Custom Button')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Cancel')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Save')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<ModalFooter className="custom-class" />);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('renders nothing when no handlers provided', () => {
|
||||
const { container } = render(<ModalFooter />);
|
||||
expect(container.querySelector('button')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('disables back button when loading', () => {
|
||||
render(<ModalFooter onBack={() => {}} showBackButton isLoading />);
|
||||
expect(screen.getByText('Back')).toBeDisabled();
|
||||
});
|
||||
});
|
||||
144
frontend/src/components/ui/__tests__/StepIndicator.test.tsx
Normal file
144
frontend/src/components/ui/__tests__/StepIndicator.test.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { StepIndicator } from '../StepIndicator';
|
||||
|
||||
const steps = [
|
||||
{ id: 1, label: 'Step 1' },
|
||||
{ id: 2, label: 'Step 2' },
|
||||
{ id: 3, label: 'Step 3' },
|
||||
];
|
||||
|
||||
describe('StepIndicator', () => {
|
||||
it('renders all steps', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={1} />);
|
||||
expect(screen.getByText('Step 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Step 2')).toBeInTheDocument();
|
||||
expect(screen.getByText('Step 3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows step numbers', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={1} />);
|
||||
expect(screen.getByText('1')).toBeInTheDocument();
|
||||
expect(screen.getByText('2')).toBeInTheDocument();
|
||||
expect(screen.getByText('3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('highlights current step', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={2} />);
|
||||
const step2Circle = screen.getByText('2').closest('div');
|
||||
expect(step2Circle).toHaveClass('bg-blue-600');
|
||||
});
|
||||
|
||||
it('shows checkmark for completed steps', () => {
|
||||
const { container } = render(<StepIndicator steps={steps} currentStep={3} />);
|
||||
const checkmarks = container.querySelectorAll('svg');
|
||||
// Steps 1 and 2 should show checkmarks
|
||||
expect(checkmarks.length).toBe(2);
|
||||
});
|
||||
|
||||
it('applies pending style to future steps', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={1} />);
|
||||
const step3Circle = screen.getByText('3').closest('div');
|
||||
expect(step3Circle).toHaveClass('bg-gray-200');
|
||||
});
|
||||
|
||||
it('shows connectors between steps by default', () => {
|
||||
const { container } = render(<StepIndicator steps={steps} currentStep={1} />);
|
||||
const connectors = container.querySelectorAll('.w-16');
|
||||
expect(connectors.length).toBe(2);
|
||||
});
|
||||
|
||||
it('hides connectors when showConnectors is false', () => {
|
||||
const { container } = render(<StepIndicator steps={steps} currentStep={1} showConnectors={false} />);
|
||||
const connectors = container.querySelectorAll('.w-16');
|
||||
expect(connectors.length).toBe(0);
|
||||
});
|
||||
|
||||
it('applies completed style to connector before current step', () => {
|
||||
const { container } = render(<StepIndicator steps={steps} currentStep={2} />);
|
||||
const connectors = container.querySelectorAll('.w-16');
|
||||
expect(connectors[0]).toHaveClass('bg-blue-600');
|
||||
expect(connectors[1]).toHaveClass('bg-gray-200');
|
||||
});
|
||||
|
||||
it('applies blue color by default', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={1} />);
|
||||
const currentStep = screen.getByText('1').closest('div');
|
||||
expect(currentStep).toHaveClass('bg-blue-600');
|
||||
});
|
||||
|
||||
it('applies brand color', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={1} color="brand" />);
|
||||
const currentStep = screen.getByText('1').closest('div');
|
||||
expect(currentStep).toHaveClass('bg-brand-600');
|
||||
});
|
||||
|
||||
it('applies green color', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={1} color="green" />);
|
||||
const currentStep = screen.getByText('1').closest('div');
|
||||
expect(currentStep).toHaveClass('bg-green-600');
|
||||
});
|
||||
|
||||
it('applies purple color', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={1} color="purple" />);
|
||||
const currentStep = screen.getByText('1').closest('div');
|
||||
expect(currentStep).toHaveClass('bg-purple-600');
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<StepIndicator steps={steps} currentStep={1} className="custom-class" />);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('centers steps', () => {
|
||||
const { container } = render(<StepIndicator steps={steps} currentStep={1} />);
|
||||
expect(container.firstChild).toHaveClass('flex', 'items-center', 'justify-center');
|
||||
});
|
||||
|
||||
it('applies active text color to current step label', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={2} />);
|
||||
const step2Label = screen.getByText('Step 2');
|
||||
expect(step2Label).toHaveClass('text-blue-600');
|
||||
});
|
||||
|
||||
it('applies pending text color to future step labels', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={1} />);
|
||||
const step3Label = screen.getByText('Step 3');
|
||||
expect(step3Label).toHaveClass('text-gray-400');
|
||||
});
|
||||
|
||||
it('applies active text color to completed step labels', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={3} />);
|
||||
const step1Label = screen.getByText('Step 1');
|
||||
expect(step1Label).toHaveClass('text-blue-600');
|
||||
});
|
||||
|
||||
it('handles single step', () => {
|
||||
const singleStep = [{ id: 1, label: 'Only Step' }];
|
||||
render(<StepIndicator steps={singleStep} currentStep={1} />);
|
||||
expect(screen.getByText('Only Step')).toBeInTheDocument();
|
||||
expect(screen.getByText('1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders step circles with correct size', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={1} />);
|
||||
const stepCircle = screen.getByText('1').closest('div');
|
||||
expect(stepCircle).toHaveClass('w-8', 'h-8');
|
||||
});
|
||||
|
||||
it('renders step circles as rounded', () => {
|
||||
render(<StepIndicator steps={steps} currentStep={1} />);
|
||||
const stepCircle = screen.getByText('1').closest('div');
|
||||
expect(stepCircle).toHaveClass('rounded-full');
|
||||
});
|
||||
|
||||
it('handles string IDs', () => {
|
||||
const stepsWithStringIds = [
|
||||
{ id: 'first', label: 'First' },
|
||||
{ id: 'second', label: 'Second' },
|
||||
];
|
||||
render(<StepIndicator steps={stepsWithStringIds} currentStep={1} />);
|
||||
expect(screen.getByText('First')).toBeInTheDocument();
|
||||
expect(screen.getByText('Second')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
160
frontend/src/components/ui/__tests__/TabGroup.test.tsx
Normal file
160
frontend/src/components/ui/__tests__/TabGroup.test.tsx
Normal file
@@ -0,0 +1,160 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { TabGroup } from '../TabGroup';
|
||||
|
||||
const tabs = [
|
||||
{ id: 'tab1', label: 'Tab 1' },
|
||||
{ id: 'tab2', label: 'Tab 2' },
|
||||
{ id: 'tab3', label: 'Tab 3', disabled: true },
|
||||
];
|
||||
|
||||
describe('TabGroup', () => {
|
||||
it('renders all tabs', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} />);
|
||||
expect(screen.getByText('Tab 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Tab 2')).toBeInTheDocument();
|
||||
expect(screen.getByText('Tab 3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('highlights active tab', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} />);
|
||||
const activeButton = screen.getByText('Tab 1').closest('button');
|
||||
expect(activeButton).toHaveClass('bg-blue-600');
|
||||
});
|
||||
|
||||
it('calls onChange when tab is clicked', () => {
|
||||
const handleChange = vi.fn();
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={handleChange} />);
|
||||
fireEvent.click(screen.getByText('Tab 2'));
|
||||
expect(handleChange).toHaveBeenCalledWith('tab2');
|
||||
});
|
||||
|
||||
it('does not call onChange for disabled tabs', () => {
|
||||
const handleChange = vi.fn();
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={handleChange} />);
|
||||
fireEvent.click(screen.getByText('Tab 3'));
|
||||
expect(handleChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies disabled styling to disabled tabs', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} />);
|
||||
const disabledButton = screen.getByText('Tab 3').closest('button');
|
||||
expect(disabledButton).toHaveClass('opacity-50');
|
||||
expect(disabledButton).toHaveClass('cursor-not-allowed');
|
||||
});
|
||||
|
||||
it('renders default variant by default', () => {
|
||||
const { container } = render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} />);
|
||||
expect(container.firstChild).toHaveClass('rounded-lg');
|
||||
});
|
||||
|
||||
it('renders underline variant', () => {
|
||||
const { container } = render(
|
||||
<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} variant="underline" />
|
||||
);
|
||||
expect(container.firstChild).toHaveClass('border-b');
|
||||
});
|
||||
|
||||
it('renders pills variant', () => {
|
||||
const { container } = render(
|
||||
<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} variant="pills" />
|
||||
);
|
||||
const activeButton = screen.getByText('Tab 1').closest('button');
|
||||
expect(activeButton).toHaveClass('rounded-full');
|
||||
});
|
||||
|
||||
it('applies small size classes', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} size="sm" />);
|
||||
const button = screen.getByText('Tab 1').closest('button');
|
||||
expect(button).toHaveClass('py-1.5');
|
||||
});
|
||||
|
||||
it('applies medium size classes by default', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} />);
|
||||
const button = screen.getByText('Tab 1').closest('button');
|
||||
expect(button).toHaveClass('py-2');
|
||||
});
|
||||
|
||||
it('applies large size classes', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} size="lg" />);
|
||||
const button = screen.getByText('Tab 1').closest('button');
|
||||
expect(button).toHaveClass('py-2.5');
|
||||
});
|
||||
|
||||
it('applies full width by default', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} />);
|
||||
const button = screen.getByText('Tab 1').closest('button');
|
||||
expect(button).toHaveClass('flex-1');
|
||||
});
|
||||
|
||||
it('can disable full width', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} fullWidth={false} />);
|
||||
const button = screen.getByText('Tab 1').closest('button');
|
||||
expect(button).not.toHaveClass('flex-1');
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(
|
||||
<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} className="custom-class" />
|
||||
);
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('applies blue active color by default', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} />);
|
||||
const activeButton = screen.getByText('Tab 1').closest('button');
|
||||
expect(activeButton).toHaveClass('bg-blue-600');
|
||||
});
|
||||
|
||||
it('applies purple active color', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} activeColor="purple" />);
|
||||
const activeButton = screen.getByText('Tab 1').closest('button');
|
||||
expect(activeButton).toHaveClass('bg-purple-600');
|
||||
});
|
||||
|
||||
it('applies green active color', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} activeColor="green" />);
|
||||
const activeButton = screen.getByText('Tab 1').closest('button');
|
||||
expect(activeButton).toHaveClass('bg-green-600');
|
||||
});
|
||||
|
||||
it('applies brand active color', () => {
|
||||
render(<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} activeColor="brand" />);
|
||||
const activeButton = screen.getByText('Tab 1').closest('button');
|
||||
expect(activeButton).toHaveClass('bg-brand-600');
|
||||
});
|
||||
|
||||
it('renders tabs with icons', () => {
|
||||
const tabsWithIcons = [
|
||||
{ id: 'tab1', label: 'Tab 1', icon: <span data-testid="icon-1">🏠</span> },
|
||||
{ id: 'tab2', label: 'Tab 2', icon: <span data-testid="icon-2">📧</span> },
|
||||
];
|
||||
render(<TabGroup tabs={tabsWithIcons} activeTab="tab1" onChange={() => {}} />);
|
||||
expect(screen.getByTestId('icon-1')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('icon-2')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders tabs with ReactNode labels', () => {
|
||||
const tabsWithNodes = [
|
||||
{ id: 'tab1', label: <strong>Bold Tab</strong> },
|
||||
];
|
||||
render(<TabGroup tabs={tabsWithNodes} activeTab="tab1" onChange={() => {}} />);
|
||||
expect(screen.getByText('Bold Tab')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies underline variant colors correctly', () => {
|
||||
render(
|
||||
<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} variant="underline" />
|
||||
);
|
||||
const activeButton = screen.getByText('Tab 1').closest('button');
|
||||
expect(activeButton).toHaveClass('border-blue-600');
|
||||
});
|
||||
|
||||
it('applies pills variant colors correctly', () => {
|
||||
render(
|
||||
<TabGroup tabs={tabs} activeTab="tab1" onChange={() => {}} variant="pills" />
|
||||
);
|
||||
const activeButton = screen.getByText('Tab 1').closest('button');
|
||||
expect(activeButton).toHaveClass('bg-blue-100');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { UnfinishedBadge } from '../UnfinishedBadge';
|
||||
|
||||
describe('UnfinishedBadge', () => {
|
||||
it('renders WIP text', () => {
|
||||
render(<UnfinishedBadge />);
|
||||
expect(screen.getByText('WIP')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders as a badge', () => {
|
||||
render(<UnfinishedBadge />);
|
||||
const badge = screen.getByText('WIP').closest('span');
|
||||
expect(badge).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses warning variant', () => {
|
||||
render(<UnfinishedBadge />);
|
||||
const badge = screen.getByText('WIP').closest('span');
|
||||
expect(badge).toHaveClass('bg-amber-100');
|
||||
});
|
||||
|
||||
it('uses pill style', () => {
|
||||
render(<UnfinishedBadge />);
|
||||
const badge = screen.getByText('WIP').closest('span');
|
||||
expect(badge).toHaveClass('rounded-full');
|
||||
});
|
||||
|
||||
it('uses small size', () => {
|
||||
render(<UnfinishedBadge />);
|
||||
const badge = screen.getByText('WIP').closest('span');
|
||||
expect(badge).toHaveClass('text-xs');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user