-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathform-error.test.tsx
More file actions
385 lines (303 loc) · 12 KB
/
form-error.test.tsx
File metadata and controls
385 lines (303 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import { zodResolver } from '@hookform/resolvers/zod';
import { FormError, TextField } from '@lambdacurry/forms';
import { Button } from '@lambdacurry/forms/ui/button';
import { render, screen } from '@testing-library/react';
import { useFetcher } from 'react-router';
import { RemixFormProvider, useRemixForm } from 'remix-hook-form';
import { z } from 'zod';
import type { ElementType, PropsWithChildren } from 'react';
// Mock useFetcher
jest.mock('react-router', () => ({
useFetcher: jest.fn(),
}));
const mockUseFetcher = useFetcher as jest.MockedFunction<typeof useFetcher>;
// Test form schema
const testSchema = z.object({
email: z.string().email('Invalid email'),
password: z.string().min(6, 'Password too short'),
});
type TestFormData = z.infer<typeof testSchema>;
// Test component wrapper
const TestFormWithError = ({
initialErrors = {},
formErrorName = '_form',
customComponents = {},
className = '',
}: {
initialErrors?: Record<string, { message: string }>;
formErrorName?: string;
customComponents?: { FormMessage?: React.ComponentType<PropsWithChildren<Record<string, unknown>>> };
className?: string;
}) => {
const mockFetcher = {
data: { errors: initialErrors },
state: 'idle' as const,
submit: jest.fn(),
Form: 'form' as ElementType,
};
mockUseFetcher.mockReturnValue(mockFetcher);
const methods = useRemixForm<TestFormData>({
resolver: zodResolver(testSchema),
defaultValues: { email: '', password: '' },
fetcher: mockFetcher,
submitConfig: { action: '/test', method: 'post' },
});
return (
<RemixFormProvider {...methods}>
<form onSubmit={methods.handleSubmit}>
<FormError name={formErrorName} className={className} components={customComponents} />
<TextField name="email" label="Email" />
<TextField name="password" label="Password" />
<Button type="submit">Submit</Button>
</form>
</RemixFormProvider>
);
};
describe('FormError Component', () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe('Basic Functionality', () => {
it('renders without errors when no form-level error exists', () => {
render(<TestFormWithError />);
// Should not display any error message
expect(screen.queryByText(/error/i)).not.toBeInTheDocument();
});
it('displays form-level error when _form error exists', () => {
const errors = {
_form: { message: 'Server error occurred' },
};
render(<TestFormWithError initialErrors={errors} />);
expect(screen.getByText('Server error occurred')).toBeInTheDocument();
});
it('does not display error when _form error does not exist', () => {
const errors = {
email: { message: 'Email is invalid' },
};
render(<TestFormWithError initialErrors={errors} />);
expect(screen.queryByText('Server error occurred')).not.toBeInTheDocument();
});
});
describe('Custom Error Keys', () => {
it('displays error for custom error key', () => {
const errors = {
general: { message: 'General form error' },
};
render(<TestFormWithError initialErrors={errors} formErrorName="general" />);
expect(screen.getByText('General form error')).toBeInTheDocument();
});
it('does not display error when custom key does not match', () => {
const errors = {
_form: { message: 'Default form error' },
};
render(<TestFormWithError initialErrors={errors} formErrorName="custom" />);
expect(screen.queryByText('Default form error')).not.toBeInTheDocument();
});
});
describe('Styling and CSS Classes', () => {
it('applies custom className to the error container', () => {
const errors = {
_form: { message: 'Test error' },
};
render(<TestFormWithError initialErrors={errors} className="custom-error-class" />);
const errorElement = screen.getByText('Test error').closest('[class*="custom-error-class"]');
expect(errorElement).toBeInTheDocument();
});
it('renders with default styling when no className provided', () => {
const errors = {
_form: { message: 'Test error' },
};
render(<TestFormWithError initialErrors={errors} />);
expect(screen.getByText('Test error')).toBeInTheDocument();
});
});
describe('Component Customization', () => {
it('uses custom FormMessage component when provided', () => {
const CustomFormMessage = ({ children, ...props }: PropsWithChildren<Record<string, unknown>>) => (
<div data-testid="custom-form-message" className="custom-message" {...props}>
Custom: {children}
</div>
);
const errors = {
_form: { message: 'Test error' },
};
render(<TestFormWithError initialErrors={errors} customComponents={{ FormMessage: CustomFormMessage }} />);
expect(screen.getByTestId('custom-form-message')).toBeInTheDocument();
expect(screen.getByText('Custom: Test error')).toBeInTheDocument();
});
it('falls back to default FormMessage when no custom component provided', () => {
const errors = {
_form: { message: 'Test error' },
};
render(<TestFormWithError initialErrors={errors} />);
expect(screen.getByText('Test error')).toBeInTheDocument();
// Should not have custom wrapper
expect(screen.queryByTestId('custom-form-message')).not.toBeInTheDocument();
});
});
describe('Integration with Form State', () => {
it('updates when form errors change', async () => {
const { rerender } = render(<TestFormWithError />);
// Initially no error
expect(screen.queryByText('New error')).not.toBeInTheDocument();
// Update with error
const errors = {
_form: { message: 'New error' },
};
rerender(<TestFormWithError initialErrors={errors} />);
expect(screen.getByText('New error')).toBeInTheDocument();
});
it('hides error when form errors are cleared', async () => {
const errors = {
_form: { message: 'Initial error' },
};
const { rerender } = render(<TestFormWithError initialErrors={errors} />);
// Initially shows error
expect(screen.getByText('Initial error')).toBeInTheDocument();
// Clear errors
rerender(<TestFormWithError initialErrors={{}} />);
expect(screen.queryByText('Initial error')).not.toBeInTheDocument();
});
});
describe('Multiple FormError Components', () => {
const MultipleFormErrorsComponent = () => {
const mockFetcher = {
data: {
errors: {
_form: { message: 'General error' },
custom: { message: 'Custom error' },
},
},
state: 'idle' as const,
submit: jest.fn(),
Form: 'form' as ElementType,
};
mockUseFetcher.mockReturnValue(mockFetcher);
const methods = useRemixForm<TestFormData>({
resolver: zodResolver(testSchema),
defaultValues: { email: '', password: '' },
fetcher: mockFetcher,
submitConfig: { action: '/test', method: 'post' },
});
return (
<RemixFormProvider {...methods}>
<form>
<FormError name="_form" className="top-error" />
<TextField name="email" label="Email" />
<FormError name="custom" className="middle-error" />
<TextField name="password" label="Password" />
<FormError name="_form" className="bottom-error" />
</form>
</RemixFormProvider>
);
};
it('renders multiple FormError components with different error keys', () => {
render(<MultipleFormErrorsComponent />);
expect(screen.getAllByText('General error')).toHaveLength(2); // top and bottom
expect(screen.getByText('Custom error')).toBeInTheDocument(); // middle
});
});
describe('Accessibility', () => {
it('has proper ARIA attributes for error messages', () => {
const errors = {
_form: { message: 'Accessibility test error' },
};
render(<TestFormWithError initialErrors={errors} />);
const errorMessage = screen.getByText('Accessibility test error');
expect(errorMessage).toHaveAttribute('data-slot', 'form-message');
});
it('is properly associated with form context', () => {
const errors = {
_form: { message: 'Form context error' },
};
render(<TestFormWithError initialErrors={errors} />);
const errorMessage = screen.getByText('Form context error');
expect(errorMessage.tagName.toLowerCase()).toBe('p');
expect(errorMessage).toHaveClass('form-message');
});
});
describe('Error Message Content', () => {
it('handles empty error messages gracefully', () => {
const errors = {
_form: { message: '' },
};
render(<TestFormWithError initialErrors={errors} />);
// Should not render anything for empty message
expect(screen.queryByText('')).not.toBeInTheDocument();
});
it('handles long error messages', () => {
const longMessage =
'This is a very long error message that should still be displayed properly even when it contains a lot of text and might wrap to multiple lines in the user interface.';
const errors = {
_form: { message: longMessage },
};
render(<TestFormWithError initialErrors={errors} />);
expect(screen.getByText(longMessage)).toBeInTheDocument();
});
it('handles special characters in error messages', () => {
const specialMessage = 'Error with special chars: <>&"\'';
const errors = {
_form: { message: specialMessage },
};
render(<TestFormWithError initialErrors={errors} />);
expect(screen.getByText(specialMessage)).toBeInTheDocument();
});
});
describe('Performance', () => {
it('does not re-render unnecessarily when unrelated form state changes', () => {
const renderSpy = jest.fn();
const CustomFormMessage = ({ children, ...props }: PropsWithChildren<Record<string, unknown>>) => {
renderSpy();
return <div {...props}>{children}</div>;
};
const errors = {
_form: { message: 'Performance test' },
};
const { rerender } = render(
<TestFormWithError initialErrors={errors} customComponents={{ FormMessage: CustomFormMessage }} />,
);
const initialRenderCount = renderSpy.mock.calls.length;
// Re-render with same errors (should not cause additional renders)
rerender(<TestFormWithError initialErrors={errors} customComponents={{ FormMessage: CustomFormMessage }} />);
expect(renderSpy.mock.calls.length).toBe(initialRenderCount);
});
});
});
describe('FormError Integration Tests', () => {
it('works correctly in a complete form submission flow', async () => {
const TestForm = () => {
const mockFetcher = {
data: null,
state: 'idle' as const,
submit: jest.fn(),
Form: 'form' as ElementType,
};
mockUseFetcher.mockReturnValue(mockFetcher);
const methods = useRemixForm<TestFormData>({
resolver: zodResolver(testSchema),
defaultValues: { email: '', password: '' },
fetcher: mockFetcher,
submitConfig: { action: '/test', method: 'post' },
});
return (
<RemixFormProvider {...methods}>
<form onSubmit={methods.handleSubmit}>
<FormError />
<TextField name="email" label="Email" />
<TextField name="password" label="Password" />
<Button type="submit">Submit</Button>
</form>
</RemixFormProvider>
);
};
render(<TestForm />);
// Form should render without errors initially
expect(screen.queryByText(/error/i)).not.toBeInTheDocument();
// Submit button should be present and functional
const submitButton = screen.getByRole('button', { name: /submit/i });
expect(submitButton).toBeInTheDocument();
// Form fields should be present
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
});
});