Add extensive form tests and enhanced error handling for auth components.

- Introduced comprehensive tests for `RegisterForm`, `PasswordResetRequestForm`, and `PasswordResetConfirmForm` covering successful submissions, validation errors, and API error handling.
- Refactored forms to handle unexpected errors gracefully and improve test coverage for edge cases.
- Updated `crypto` and `storage` modules with robust error handling for storage issues and encryption key management.
- Removed unused `axios-mock-adapter` dependency for cleaner dependency management.
This commit is contained in:
Felipe Cardoso
2025-11-01 05:24:26 +01:00
parent 035e6af446
commit ee938ce6a6
15 changed files with 934 additions and 536 deletions

View File

@@ -7,6 +7,31 @@ import userEvent from '@testing-library/user-event';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { LoginForm } from '@/components/auth/LoginForm';
// Mock the useLogin hook
const mockMutateAsync = jest.fn();
const mockUseLogin = jest.fn(() => ({
mutateAsync: mockMutateAsync,
mutate: jest.fn(),
isPending: false,
isError: false,
isSuccess: false,
isIdle: true,
error: null,
data: undefined,
status: 'idle' as const,
variables: undefined,
reset: jest.fn(),
context: undefined,
failureCount: 0,
failureReason: null,
isPaused: false,
submittedAt: 0,
}));
jest.mock('@/lib/api/hooks/useAuth', () => ({
useLogin: () => mockUseLogin(),
}));
// Mock router
jest.mock('next/navigation', () => ({
useRouter: () => ({
@@ -38,6 +63,11 @@ const createWrapper = () => {
};
describe('LoginForm', () => {
beforeEach(() => {
mockMutateAsync.mockClear();
mockUseLogin.mockClear();
});
it('renders login form with email and password fields', () => {
render(<LoginForm />, { wrapper: createWrapper() });
@@ -59,9 +89,6 @@ describe('LoginForm', () => {
});
});
// Note: Email validation is primarily handled by HTML5 type="email" attribute
// Zod provides additional validation layer
it('shows password requirements validation', async () => {
const user = userEvent.setup();
render(<LoginForm />, { wrapper: createWrapper() });
@@ -92,6 +119,162 @@ describe('LoginForm', () => {
expect(screen.getByRole('link', { name: /forgot password/i })).toBeInTheDocument();
});
// Note: Async submission tests require API mocking with MSW
// Will be added in Phase 9 (Testing Infrastructure)
describe('Form submission', () => {
it('calls mutateAsync with form data on valid submission', async () => {
const user = userEvent.setup();
mockMutateAsync.mockResolvedValueOnce(undefined);
render(<LoginForm />, { wrapper: createWrapper() });
const emailInput = screen.getByLabelText(/email/i);
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByRole('button', { name: /sign in/i });
await user.type(emailInput, 'test@example.com');
await user.type(passwordInput, 'Password123');
await user.click(submitButton);
await waitFor(() => {
expect(mockMutateAsync).toHaveBeenCalledWith({
email: 'test@example.com',
password: 'Password123',
});
});
});
it('calls onSuccess callback after successful login', async () => {
const user = userEvent.setup();
const onSuccess = jest.fn();
mockMutateAsync.mockResolvedValueOnce(undefined);
render(<LoginForm onSuccess={onSuccess} />, { wrapper: createWrapper() });
const emailInput = screen.getByLabelText(/email/i);
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByRole('button', { name: /sign in/i });
await user.type(emailInput, 'test@example.com');
await user.type(passwordInput, 'Password123');
await user.click(submitButton);
await waitFor(() => {
expect(onSuccess).toHaveBeenCalled();
});
});
it('displays general error message from API', async () => {
const user = userEvent.setup();
const apiError = [
{
code: 'AUTH_001',
message: 'Invalid credentials',
},
];
mockMutateAsync.mockRejectedValueOnce(apiError);
render(<LoginForm />, { wrapper: createWrapper() });
const emailInput = screen.getByLabelText(/email/i);
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByRole('button', { name: /sign in/i });
await user.type(emailInput, 'test@example.com');
await user.type(passwordInput, 'WrongPassword1');
await user.click(submitButton);
await waitFor(() => {
expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
});
});
it('displays field-specific errors from API', async () => {
const user = userEvent.setup();
const apiError = [
{
code: 'VALIDATION_ERROR',
message: 'Invalid email format',
field: 'email',
},
{
code: 'VALIDATION_ERROR',
message: 'Password is too weak',
field: 'password',
},
];
mockMutateAsync.mockRejectedValueOnce(apiError);
render(<LoginForm />, { wrapper: createWrapper() });
const emailInput = screen.getByLabelText(/email/i);
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByRole('button', { name: /sign in/i });
await user.type(emailInput, 'test@example.com');
await user.type(passwordInput, 'Password123');
await user.click(submitButton);
await waitFor(() => {
expect(screen.getByText('Invalid email format')).toBeInTheDocument();
expect(screen.getByText('Password is too weak')).toBeInTheDocument();
});
});
it('displays generic error for unexpected error format', async () => {
const user = userEvent.setup();
const unexpectedError = new Error('Network error');
mockMutateAsync.mockRejectedValueOnce(unexpectedError);
render(<LoginForm />, { wrapper: createWrapper() });
const emailInput = screen.getByLabelText(/email/i);
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByRole('button', { name: /sign in/i });
await user.type(emailInput, 'test@example.com');
await user.type(passwordInput, 'Password123');
await user.click(submitButton);
await waitFor(() => {
expect(screen.getByText('An unexpected error occurred. Please try again.')).toBeInTheDocument();
});
});
it('clears previous errors on new submission', async () => {
const user = userEvent.setup();
const apiError = [
{
code: 'AUTH_001',
message: 'Invalid credentials',
},
];
// First submission fails
mockMutateAsync.mockRejectedValueOnce(apiError);
render(<LoginForm />, { wrapper: createWrapper() });
const emailInput = screen.getByLabelText(/email/i);
const passwordInput = screen.getByLabelText(/password/i);
const submitButton = screen.getByRole('button', { name: /sign in/i });
await user.type(emailInput, 'test@example.com');
await user.type(passwordInput, 'WrongPassword1');
await user.click(submitButton);
await waitFor(() => {
expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
});
// Second submission succeeds
mockMutateAsync.mockResolvedValueOnce(undefined);
await user.clear(passwordInput);
await user.type(passwordInput, 'CorrectPassword1');
await user.click(submitButton);
await waitFor(() => {
expect(screen.queryByText('Invalid credentials')).not.toBeInTheDocument();
});
});
});
});