Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import z from 'zod'
3import {
4 createErrorMap,
5 createErrorVisibility,
6 createValidator,
7 createValidators,
8 formOptions,
9} from '../src'
10β
11describe('validation public helpers', () => {
12 it('returns form options unchanged at runtime', () => {
13 const options = { defaultValues: { name: 'Ada' } }
14 const triggers: Array<'change'> = ['change']
15 const schema = z.object({ name: z.string() })
16 const schemaOptions = {
17 ...options,
18 validators: [
19 {
20 run: schema,
21 triggers,
22 },
23 ],
24 }
25β
26 expect(formOptions(options)).toBe(options)
27 expect(formOptions.strictSchema(schema, schemaOptions)).toBe(schemaOptions)
28 expect(formOptions.looseSchema(schema, schemaOptions)).toBe(schemaOptions)
29 })
30β
31 it('creates validators by pairing options with run functions', () => {
32 const run = () => null
33 const validator = createValidator({
34 bailIfInvalid: true,
35 triggers: ['change'],
36 })(run)
37β
38 expect(validator).toEqual({
39 bailIfInvalid: true,
40 triggers: ['change'],
41 run,
42 })
43 })
44β
45 it('creates multiple validators from option and run tuples', () => {
46 const firstRun = () => null
47 const secondRun = () => ({ message: 'Required' })
48β
49 const validators = createValidators([
50 { triggers: ['change'] },
51 { bailIfInvalid: true, triggers: ['blur'] },
52 ])(firstRun, secondRun)
53β
54 expect(validators).toEqual([
55 { triggers: ['change'], run: firstRun },
56 { bailIfInvalid: true, triggers: ['blur'], run: secondRun },
57 ])
58 })
59β
60 it('returns reusable error visibility callbacks unchanged', () => {
61 const visibility = () => true
62β
63 expect(createErrorVisibility(visibility)).toBe(visibility)
64 })
65β
66 it('creates mutable validation error maps', () => {
67 const errors = createErrorMap<{ name: string; age: number }>()
68β
69 expect(errors).toEqual({ fields: {} })
70 errors.fields.name = undefined
71 errors.fields.age = 'Age is required'
72 errors.form = 'Form is invalid'
73β
74 expect(errors).toEqual({
75 form: 'Form is invalid',
76 fields: { name: undefined, age: 'Age is required' },
77 })
78 })
79β
80 it('returns the prefilled validation error map', () => {
81 const initial = {
82 form: 'Form is invalid',
83 fields: { name: 'Name is required' },
84 }
85β
86 const errors = createErrorMap(initial)
87β
88 expect(errors).toBe(initial)
89 })
90β
91 it('preserves falsy form errors in the initial error map', () => {
92 const initial = {
93 form: '',
94 fields: {},
95 }
96β
97 const errors = createErrorMap(initial)
98β
99 expect(errors).toBe(initial)
100 expect(errors).toHaveProperty('form', '')
101 })
102})