Open History to see the last commit
1import { describe, expect, it, onTestFinished, vi } from 'vitest'
2import { z } from 'zod'
3import { formOptions } from '../src'
4import { InternalFormApi } from '../src/FormApi/FormApi.lib'
5import { InternalFormGroupApi } from '../src/FormGroupApi/FormGroupApi.lib'
6import { validateServerValues } from '../src/internals'
7import type { FormValidatorContext } from '../src'
8β
9describe('validator outputs', () => {
10 it('forwards arbitrary payloads without mutation or loss of identity', async () => {
11 const payloads = [
12 undefined,
13 null,
14 false,
15 0,
16 '',
17 1n,
18 Symbol('payload'),
19 Object.freeze({ message: 'This is data', fields: { name: 'Also data' } }),
20 Object.freeze(['data']),
21 () => 'data',
22 ]
23 const onSubmit = vi.fn()
24 const form = new InternalFormApi(
25 formOptions({
26 defaultValues: { name: 'Tony' },
27 validators: payloads.map((payload) => ({
28 run: ({ createOutput }: FormValidatorContext<{ name: string }>) =>
29 createOutput(payload),
30 triggers: [],
31 })),
32 onSubmit,
33 }),
34 )
35β
36 await form.handleSubmit()
37β
38 expect(onSubmit).toHaveBeenCalledWith(
39 expect.objectContaining({
40 value: { name: 'Tony' },
41 validatorOutputs: payloads,
42 }),
43 )
44 const { validatorOutputs } = onSubmit.mock.lastCall![0]
45 for (const [index, payload] of payloads.entries()) {
46 expect(validatorOutputs[index]).toBe(payload)
47 }
48 expect(form.state.errors).toEqual([])
49 expect(form.state.isSubmitSuccessful).toBe(true)
50 })
51β
52 it('aligns schema, sync, async, absent, and skipped outputs by validator index', async () => {
53 const skipped = vi.fn()
54 const onSubmit = vi.fn()
55 const form = new InternalFormApi(
56 formOptions({
57 defaultValues: { name: ' Tony ' },
58 validators: [
59 { run: z.object({ name: z.string().trim() }), triggers: [] },
60 {
61 run: ({ value, createOutput }) => createOutput(value.name.length),
62 triggers: [],
63 },
64 {
65 run: async ({ value, createOutput }) =>
66 createOutput(value.name.trim().toUpperCase()),
67 triggers: [],
68 },
69 { run: () => undefined, triggers: [] },
70 { run: skipped, triggers: [], skipOnSubmit: true },
71 ],
72 onSubmit,
73 }),
74 )
75β
76 await form.handleSubmit()
77β
78 expect(onSubmit).toHaveBeenCalledWith(
79 expect.objectContaining({
80 value: { name: ' Tony ' },
81 validatorOutputs: [{ name: 'Tony' }, 6, 'TONY', undefined, undefined],
82 }),
83 )
84 expect(skipped).not.toHaveBeenCalled()
85 })
86β
87 it('keeps error branches as errors and accepts a later output branch', async () => {
88 const onSubmit = vi.fn()
89 const form = new InternalFormApi(
90 formOptions({
91 defaultValues: { name: '' },
92 validators: [
93 {
94 run: ({ value, createOutput }) => {
95 if (!value.name) return { message: 'Required', code: 'required' }
96 return createOutput({ name: value.name.trim() })
97 },
98 triggers: [],
99 },
100 ],
101 onSubmit,
102 }),
103 )
104β
105 await form.handleSubmit()
106β
107 expect(onSubmit).not.toHaveBeenCalled()
108 expect(form.state.errors).toEqual([
109 { message: 'Required', code: 'required' },
110 ])
111β
112 form.setFieldValue('name', ' Tony ')
113 await form.handleSubmit()
114β
115 expect(form.state.errors).toEqual([])
116 expect(onSubmit).toHaveBeenCalledWith(
117 expect.objectContaining({ validatorOutputs: [{ name: 'Tony' }] }),
118 )
119 })
120β
121 it('clears earlier outputs when a later submission skips or succeeds without output', async () => {
122 let shouldSkip = false
123 let produceOutput = true
124 const onSubmit = vi.fn()
125 const form = new InternalFormApi(
126 formOptions({
127 defaultValues: { name: 'Tony' },
128 validators: [
129 {
130 run: ({ value, createOutput }) =>
131 produceOutput ? createOutput(value.name) : [],
132 skipOnSubmit: () => shouldSkip,
133 triggers: [],
134 },
135 ],
136 onSubmit,
137 }),
138 )
139β
140 await form.handleSubmit()
141 expect(onSubmit).toHaveBeenLastCalledWith(
142 expect.objectContaining({ validatorOutputs: ['Tony'] }),
143 )
144β
145 shouldSkip = true
146 await form.handleSubmit()
147 expect(onSubmit).toHaveBeenLastCalledWith(
148 expect.objectContaining({ validatorOutputs: [undefined] }),
149 )
150β
151 shouldSkip = false
152 await form.handleSubmit()
153 expect(onSubmit).toHaveBeenLastCalledWith(
154 expect.objectContaining({ validatorOutputs: ['Tony'] }),
155 )
156β
157 produceOutput = false
158 await form.handleSubmit()
159 expect(onSubmit).toHaveBeenLastCalledWith(
160 expect.objectContaining({ validatorOutputs: [undefined] }),
161 )
162 })
163β
164 it('treats change and blur outputs as success without retaining them for submission', async () => {
165 const onSubmit = vi.fn()
166 const nextValidator = vi.fn(() => undefined)
167 const form = new InternalFormApi(
168 formOptions({
169 defaultValues: { name: 'Tony' },
170 validators: [
171 {
172 run: ({ createOutput }) => createOutput('event output'),
173 triggers: ['change', 'blur'],
174 skipOnSubmit: true,
175 },
176 {
177 run: nextValidator,
178 triggers: ['change', 'blur'],
179 bailIfInvalid: true,
180 },
181 ],
182 onSubmit,
183 }),
184 )
185β
186 const changeErrors = await form.validate('change')
187 const blurErrors = await form.validate('blur')
188β
189 expect(changeErrors).toEqual([])
190 expect(blurErrors).toEqual([])
191 expect(nextValidator).toHaveBeenCalledWith(
192 expect.objectContaining({ event: 'blur' }),
193 )
194β
195 await form.handleSubmit()
196 expect(onSubmit).toHaveBeenCalledWith(
197 expect.objectContaining({ validatorOutputs: [undefined, undefined] }),
198 )
199 })
200β
201 it('treats sync and async mount outputs as success and preserves synchronous mount work', async () => {
202 for (const asyncOutput of [false, true]) {
203 const nextValidator = vi.fn(() => undefined)
204 const onSubmit = vi.fn()
205 const form = new InternalFormApi(
206 formOptions({
207 defaultValues: { name: 'Tony' },
208 validators: [
209 {
210 run: ({ createOutput }) =>
211 asyncOutput
212 ? Promise.resolve(createOutput('mount output'))
213 : createOutput('mount output'),
214 runOnMount: true,
215 skipOnSubmit: true,
216 triggers: [],
217 },
218 {
219 run: nextValidator,
220 runOnMount: true,
221 triggers: [],
222 bailIfInvalid: true,
223 },
224 ],
225 onSubmit,
226 }),
227 )
228β
229 const cleanup = form.mount()
230 onTestFinished(cleanup)
231 if (!asyncOutput) expect(nextValidator).toHaveBeenCalled()
232 await expect.poll(() => form.state.isValidating).toBe(false)
233β
234 expect(nextValidator).toHaveBeenCalledWith(
235 expect.objectContaining({ event: 'mount' }),
236 )
237 expect(form.state.errors).toEqual([])
238β
239 await form.handleSubmit()
240 expect(onSubmit).toHaveBeenCalledWith(
241 expect.objectContaining({ validatorOutputs: [undefined, undefined] }),
242 )
243 }
244 })
245β
246 it('provides group outputs from fresh validation and clears skipped slots', async () => {
247 let shouldRun = true
248 const onSubmit = vi.fn()
249 const form = new InternalFormApi({
250 defaultValues: { guest: { name: ' Tony ' } },
251 })
252 const group = new InternalFormGroupApi({
253 form,
254 name: 'guest',
255 validators: [
256 {
257 run: async ({ value, createOutput }) =>
258 createOutput({ name: value.name.trim() }),
259 runOnMount: true,
260 skipOnSubmit: () => !shouldRun,
261 triggers: ['change'],
262 },
263 ],
264 onSubmit,
265 })
266β
267 group.mount()
268 onTestFinished(() => group._cleanup())
269 await expect.poll(() => group.state.isValidating).toBe(false)
270 const errors = await group.validate('change')
271 expect(errors).toEqual([])
272 expect(group.state.errors).toEqual([])
273β
274 await group.handleSubmit()
275 expect(onSubmit).toHaveBeenLastCalledWith(
276 expect.objectContaining({ validatorOutputs: [{ name: 'Tony' }] }),
277 )
278β
279 shouldRun = false
280 await group.handleSubmit()
281 expect(onSubmit).toHaveBeenLastCalledWith(
282 expect.objectContaining({ validatorOutputs: [undefined] }),
283 )
284 })
285β
286 it('returns separate server outputs only for server-triggered validators', async () => {
287 const options = formOptions({
288 defaultValues: { name: '' },
289 validators: [
290 {
291 run: ({ createOutput }) => createOutput('client'),
292 triggers: ['change'],
293 },
294 { run: z.object({ name: z.string().trim() }), triggers: ['server'] },
295 {
296 run: async ({ value, createOutput }) =>
297 createOutput(value.name.length),
298 triggers: ['server'],
299 skipOnSubmit: true,
300 },
301 ],
302 })
303β
304 const result = await validateServerValues(options, { name: ' Tony ' })
305β
306 expect(result).toEqual({
307 success: true,
308 values: { name: ' Tony ' },
309 validatorOutputs: [undefined, { name: 'Tony' }, 6],
310 })
311 })
312β
313 it('consumes output wrappers before serializing failed server validation', async () => {
314 const options = formOptions({
315 defaultValues: { name: '' },
316 validators: [
317 {
318 run: ({ createOutput }) => createOutput({ name: 'Tony' }),
319 triggers: ['server'],
320 },
321 { run: () => 'Rejected', triggers: ['server'] },
322 ],
323 })
324β
325 const result = await validateServerValues(options, { name: 'Tony' })
326β
327 expect(result.success).toBe(false)
328 if (result.success) throw new Error('Expected failure')
329 const serialized = JSON.parse(JSON.stringify(result.serverState))
330 expect(serialized.validationResults).toEqual([
331 {
332 validatorIndex: 0,
333 result: null,
334 output: { name: 'Tony' },
335 hasOutput: true,
336 },
337 { validatorIndex: 1, result: 'Rejected', output: null, hasOutput: false },
338 ])
339 })
340})