|
| 1 | +import { describe, expect, it } from 'vitest' |
| 2 | +import { execValidator } from '../src/createServerFn' |
| 3 | +import type { AnyValidator } from '@tanstack/router-core' |
| 4 | + |
| 5 | +/** |
| 6 | + * A Standard Schema validator whose issues carry a bigint. `JSON.stringify` |
| 7 | + * throws on one, so these cover the server-function side going back to |
| 8 | + * serializing the issues raw: the failure would surface as a complaint about |
| 9 | + * serializing a BigInt rather than the validation message. |
| 10 | + */ |
| 11 | +function failingValidator(issues: Array<Record<string, unknown>>) { |
| 12 | + return { |
| 13 | + '~standard': { |
| 14 | + validate: () => ({ issues }), |
| 15 | + }, |
| 16 | + } as unknown as AnyValidator |
| 17 | +} |
| 18 | + |
| 19 | +describe('execValidator with a Standard Schema validator', () => { |
| 20 | + it('reports the issue rather than failing to serialize it', async () => { |
| 21 | + const validator = failingValidator([ |
| 22 | + { message: 'Expected number', path: ['field'], received: 1n }, |
| 23 | + ]) |
| 24 | + |
| 25 | + const error = await execValidator(validator, {}).then( |
| 26 | + () => undefined, |
| 27 | + (err: unknown) => err as Error, |
| 28 | + ) |
| 29 | + |
| 30 | + expect(error).toBeInstanceOf(Error) |
| 31 | + expect(error?.message).toBe('field: Expected number') |
| 32 | + expect(error?.message).not.toMatch(/BigInt|serialize/i) |
| 33 | + }) |
| 34 | + |
| 35 | + it('reports every issue with its path', async () => { |
| 36 | + const validator = failingValidator([ |
| 37 | + { message: 'Required', path: ['name'] }, |
| 38 | + { message: 'Too long', path: ['tags', 0] }, |
| 39 | + { message: 'Invalid input' }, |
| 40 | + ]) |
| 41 | + |
| 42 | + const error = await execValidator(validator, {}).then( |
| 43 | + () => undefined, |
| 44 | + (err: unknown) => err as Error, |
| 45 | + ) |
| 46 | + |
| 47 | + expect(error?.message).toBe( |
| 48 | + 'name: Required\ntags[0]: Too long\nInvalid input', |
| 49 | + ) |
| 50 | + }) |
| 51 | + |
| 52 | + it('passes the parsed value through when validation succeeds', async () => { |
| 53 | + const validator = { |
| 54 | + '~standard': { |
| 55 | + validate: () => ({ value: { ok: true } }), |
| 56 | + }, |
| 57 | + } as unknown as AnyValidator |
| 58 | + |
| 59 | + await expect(execValidator(validator, {})).resolves.toEqual({ ok: true }) |
| 60 | + }) |
| 61 | +}) |
0 commit comments