Skip to content

Commit

Permalink
Added another test.
Browse files Browse the repository at this point in the history
Fixes #516
  • Loading branch information
ciscoheat committed Nov 30, 2024
1 parent 0289a8b commit 94a28d9
Showing 1 changed file with 35 additions and 22 deletions.
57 changes: 35 additions & 22 deletions src/tests/zodUnion.test.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,52 @@
import type { ValidationAdapter } from '$lib/adapters/adapters.js';
import { zod } from '$lib/adapters/zod.js';
import { superValidate } from '$lib/superValidate.js';
import { stringify } from 'devalue';
import { describe, test } from 'vitest';
import { describe, expect, test } from 'vitest';
import { z } from 'zod';

const ZodSchema = z.object({
addresses: z.object({
additional: z.discriminatedUnion('type', [
z.object({
type: z.literal('poBox'),
name: z.string().min(1, 'min len').max(10, 'max len')
}),
z.object({
type: z.literal('none')
})
])
})
});
const FormSchema = zod(ZodSchema);
type FormSchema = (typeof FormSchema)['defaults'];

async function validate(data: unknown) {
async function validate(data: unknown, schema: ValidationAdapter<Record<string, unknown>>) {
const formInput = new FormData();

formInput.set('__superform_json', stringify(data));
try {
await superValidate(formInput, FormSchema);
return await superValidate(formInput, schema);
} catch (err) {
console.error(err);
//
throw err;
}
}

describe('Demo', () => {
describe('Default discriminated union values 1', () => {
const schema = z.discriminatedUnion('type', [
z.object({ type: z.literal('empty') }),
z.object({ type: z.literal('extra'), options: z.string().array() })
]);

test('Union with schema', async () => {
const form = await validate({ type: 'extra' }, zod(schema));
expect(form.data).toEqual({ type: 'extra', options: [] });
});
});

describe('Default discriminated union values 2', () => {
const ZodSchema = z.object({
addresses: z.object({
additional: z.discriminatedUnion('type', [
z.object({
type: z.literal('poBox'),
name: z.string().min(1, 'min len').max(10, 'max len')
}),
z.object({
type: z.literal('none')
})
])
})
});
const FormSchema = zod(ZodSchema);
type FormSchema = (typeof FormSchema)['defaults'];

test('Bad', async () => {
const data = {
addresses: {
Expand All @@ -43,7 +56,7 @@ describe('Demo', () => {
}
}
} satisfies FormSchema;
await validate(data);
await validate(data, FormSchema);
});

test('Good', async () => {
Expand All @@ -54,6 +67,6 @@ describe('Demo', () => {
}
}
} satisfies FormSchema;
await validate(data);
await validate(data, FormSchema);
});
});

0 comments on commit 94a28d9

Please sign in to comment.