Skip to content

Commit 94a28d9

Browse files
committed
Added another test.
Fixes #516
1 parent 0289a8b commit 94a28d9

File tree

1 file changed

+35
-22
lines changed

1 file changed

+35
-22
lines changed

src/tests/zodUnion.test.ts

Lines changed: 35 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,52 @@
1+
import type { ValidationAdapter } from '$lib/adapters/adapters.js';
12
import { zod } from '$lib/adapters/zod.js';
23
import { superValidate } from '$lib/superValidate.js';
34
import { stringify } from 'devalue';
4-
import { describe, test } from 'vitest';
5+
import { describe, expect, test } from 'vitest';
56
import { z } from 'zod';
67

7-
const ZodSchema = z.object({
8-
addresses: z.object({
9-
additional: z.discriminatedUnion('type', [
10-
z.object({
11-
type: z.literal('poBox'),
12-
name: z.string().min(1, 'min len').max(10, 'max len')
13-
}),
14-
z.object({
15-
type: z.literal('none')
16-
})
17-
])
18-
})
19-
});
20-
const FormSchema = zod(ZodSchema);
21-
type FormSchema = (typeof FormSchema)['defaults'];
22-
23-
async function validate(data: unknown) {
8+
async function validate(data: unknown, schema: ValidationAdapter<Record<string, unknown>>) {
249
const formInput = new FormData();
2510

2611
formInput.set('__superform_json', stringify(data));
2712
try {
28-
await superValidate(formInput, FormSchema);
13+
return await superValidate(formInput, schema);
2914
} catch (err) {
3015
console.error(err);
3116
//
3217
throw err;
3318
}
3419
}
3520

36-
describe('Demo', () => {
21+
describe('Default discriminated union values 1', () => {
22+
const schema = z.discriminatedUnion('type', [
23+
z.object({ type: z.literal('empty') }),
24+
z.object({ type: z.literal('extra'), options: z.string().array() })
25+
]);
26+
27+
test('Union with schema', async () => {
28+
const form = await validate({ type: 'extra' }, zod(schema));
29+
expect(form.data).toEqual({ type: 'extra', options: [] });
30+
});
31+
});
32+
33+
describe('Default discriminated union values 2', () => {
34+
const ZodSchema = z.object({
35+
addresses: z.object({
36+
additional: z.discriminatedUnion('type', [
37+
z.object({
38+
type: z.literal('poBox'),
39+
name: z.string().min(1, 'min len').max(10, 'max len')
40+
}),
41+
z.object({
42+
type: z.literal('none')
43+
})
44+
])
45+
})
46+
});
47+
const FormSchema = zod(ZodSchema);
48+
type FormSchema = (typeof FormSchema)['defaults'];
49+
3750
test('Bad', async () => {
3851
const data = {
3952
addresses: {
@@ -43,7 +56,7 @@ describe('Demo', () => {
4356
}
4457
}
4558
} satisfies FormSchema;
46-
await validate(data);
59+
await validate(data, FormSchema);
4760
});
4861

4962
test('Good', async () => {
@@ -54,6 +67,6 @@ describe('Demo', () => {
5467
}
5568
}
5669
} satisfies FormSchema;
57-
await validate(data);
70+
await validate(data, FormSchema);
5871
});
5972
});

0 commit comments

Comments
 (0)