-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzod.test.ts
59 lines (47 loc) · 1.71 KB
/
zod.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { describe, test, expect } from 'vitest'
import { z } from 'zod'
import { protectWithSchema } from './zod.js'
describe('protectWithSchema', () => {
// Define a test schema
const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
})
test('should validate and return data when schema matches', async () => {
const validData = {
id: 1,
name: 'John Doe',
email: '[email protected]',
}
const promise = Promise.resolve(validData)
const [result, error] = await protectWithSchema(promise, UserSchema)
expect(error).toBeUndefined()
expect(result).toEqual(validData)
})
test('should return validation error when data does not match schema', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const invalidData: any = {
id: '1', // should be number
name: 'John Doe',
email: '[email protected]',
}
const promise = Promise.resolve(invalidData)
const [result, error] = await protectWithSchema(promise, UserSchema)
expect(result).toBeUndefined()
expect(error).toBeInstanceOf(z.ZodError)
})
test('should handle promise rejection', async () => {
const promiseError = new Error('Network error')
const promise = Promise.reject(promiseError)
const [result, error] = await protectWithSchema(promise, UserSchema)
expect(result).toBeUndefined()
expect(error).toBe(promiseError)
})
test('should handle null or undefined promise results', async () => {
const promise = Promise.resolve(null)
const [result, error] = await protectWithSchema(promise, UserSchema)
expect(result).toBeUndefined()
expect(error).toBeInstanceOf(z.ZodError)
})
})