-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zod-custom-faker.test.ts
43 lines (35 loc) · 1023 Bytes
/
zod-custom-faker.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
import * as z from 'zod'
import { fake, installCustom, ZodTypeFaker, runFake, install } from '../src'
// 1/5. define custom schema
const pxSchema = z.custom<`${number}px`>(val => {
return typeof val === 'string' ? /^\d+px$/.test(val) : false
})
// 2/5. define custom faker
class pxFaker extends ZodTypeFaker<typeof pxSchema> {
fake(): `${number}px` {
// you can use `runFake` to generate fake data
return `${runFake(faker => faker.number.int({ min: 0 }))}px`
// or use `randexp` if applicable
// return randexp(/[1-9]\d+?px/) as `${number}px`
}
}
beforeEach(() => {
// 3/5. install basic faker
install()
// 4/5. install custom faker
installCustom(pxSchema, pxFaker)
})
test('basic', () => {
// 5/5. use it
const data = fake(pxSchema)
expect(pxSchema.safeParse(data).success).toBe(true)
})
test('integration', () => {
const schema = z
.object({
padding: pxSchema,
})
.strict()
const data = fake(schema)
expect(schema.safeParse(data).success).toBe(true)
})