|
| 1 | +import { superValidate } from '$lib/server'; |
| 2 | +import { expect, test, describe, assert } from 'vitest'; |
| 3 | +import { z } from 'zod'; |
| 4 | +import { entityData } from '$lib/schemaEntity'; |
| 5 | + |
| 6 | +describe('Schema errors with arrays and objects', () => { |
| 7 | + const schema = z.object({ |
| 8 | + tags: z |
| 9 | + .object({ |
| 10 | + id: z.number(), |
| 11 | + names: z.string().min(2).array(), |
| 12 | + test: z.union([z.string(), z.string().array()]) |
| 13 | + }) |
| 14 | + .array() |
| 15 | + .min(2) |
| 16 | + }); |
| 17 | + |
| 18 | + test('Schema shape traversal', () => { |
| 19 | + expect(entityData(schema).errorShape).toStrictEqual({ |
| 20 | + tags: { names: {}, test: {} } |
| 21 | + }); |
| 22 | + }); |
| 23 | + |
| 24 | + test('Array errors with nested errors', async () => { |
| 25 | + const form = await superValidate( |
| 26 | + { tags: [{ id: 123, names: ['a'], test: 'test' }] }, |
| 27 | + schema |
| 28 | + ); |
| 29 | + expect(form.errors.tags?._errors).toEqual([ |
| 30 | + 'Array must contain at least 2 element(s)' |
| 31 | + ]); |
| 32 | + expect(form.errors.tags?.[0].names?.[0]).toEqual([ |
| 33 | + 'String must contain at least 2 character(s)' |
| 34 | + ]); |
| 35 | + }); |
| 36 | + |
| 37 | + test('Array errors without nested errors', async () => { |
| 38 | + const form = await superValidate( |
| 39 | + { tags: [{ id: 123, names: ['aa'], test: ['aaa'] }] }, |
| 40 | + schema |
| 41 | + ); |
| 42 | + expect(form.errors.tags?._errors).toEqual([ |
| 43 | + 'Array must contain at least 2 element(s)' |
| 44 | + ]); |
| 45 | + expect(form.errors.tags?.[0]).toBeUndefined(); |
| 46 | + }); |
| 47 | +}); |
| 48 | + |
| 49 | +test('Refined errors on leaf node', async () => { |
| 50 | + const iceCream = z |
| 51 | + .object({ |
| 52 | + scoops: z.number().int().min(1).default(1), |
| 53 | + flavours: z |
| 54 | + .string() |
| 55 | + .array() |
| 56 | + .min(1, 'Please select at least one flavour') |
| 57 | + .default(['Mint choc chip']) |
| 58 | + }) |
| 59 | + .refine((data) => data.flavours.length <= data.scoops, { |
| 60 | + message: "Can't order more flavours than scoops!", |
| 61 | + path: ['flavours'] |
| 62 | + }); |
| 63 | + |
| 64 | + const form = await superValidate( |
| 65 | + { scoops: 1, flavours: ['Mint choc chip', 'Raspberry ripple'] }, |
| 66 | + iceCream |
| 67 | + ); |
| 68 | + |
| 69 | + assert(form.valid == false); |
| 70 | + expect(form.errors).toStrictEqual({ |
| 71 | + flavours: ["Can't order more flavours than scoops!"] |
| 72 | + }); |
| 73 | +}); |
0 commit comments