forked from anatine/zod-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzod-mock.spec.ts
809 lines (708 loc) · 26 KB
/
zod-mock.spec.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
import { z } from 'zod';
import { generateMock, ZodMockError } from './zod-mock';
import { faker, Faker } from '@faker-js/faker';
import { FakerFunction } from './zod-mockery-map';
describe('zod-mock', () => {
it('should generate a mock object using faker', () => {
enum NativeEnum {
a = 1,
b = 2,
}
const schema = z.object({
uid: z.string().nonempty(),
theme: z.enum([`light`, `dark`]),
name: z.string(),
firstName: z.string(),
email: z.string().email().optional(),
phoneNumber: z.string().min(10).optional(),
avatar: z.string().url().optional(),
jobTitle: z.string().optional(),
otherUserEmails: z.array(z.string().email()),
stringArrays: z.array(z.string()),
stringLength: z.string().transform((val) => val.length),
numberCount: z.number().transform((item) => `total value = ${item}`),
age: z.number().min(18).max(120),
record: z.record(z.string(), z.number()),
nativeEnum: z.nativeEnum(NativeEnum),
set: z.set(z.string()),
map: z.map(z.string(), z.number()),
discriminatedUnion: z.discriminatedUnion('discriminator', [
z.object({ discriminator: z.literal('a'), a: z.boolean() }),
z.object({ discriminator: z.literal('b'), b: z.string() }),
]),
readonly: z.boolean().readonly(),
});
const mockData = generateMock(schema);
expect(typeof mockData.uid).toEqual('string');
expect(
mockData.theme === 'light' || mockData.theme === 'dark'
).toBeTruthy();
expect(mockData.email).toEqual(expect.stringMatching(/\S+@\S+\.\S+/));
expect(mockData.avatar).toEqual(
expect.stringMatching(
/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?$/i
)
);
expect(typeof mockData.phoneNumber).toEqual('string');
expect(typeof mockData.jobTitle).toEqual('string');
expect(typeof mockData.stringLength).toEqual('number');
expect(typeof mockData.numberCount).toEqual('string');
expect(mockData.age).toBeGreaterThanOrEqual(18);
expect(mockData.age).toBeLessThanOrEqual(120);
expect(typeof mockData.record).toEqual('object');
expect(typeof Object.values(mockData.record)[0]).toEqual('number');
expect(mockData.nativeEnum === 1 || mockData.nativeEnum === 2);
expect(mockData.set).toBeTruthy();
expect(mockData.map).toBeTruthy();
expect(mockData.discriminatedUnion).toBeTruthy();
expect(typeof mockData.readonly).toEqual('boolean');
});
it('should generate mock data of the appropriate type when the field names overlap Faker properties that are not valid functions', () => {
const schema = z.object({
// the following fields represent non function properties in Faker
lorem: z.string(),
phoneNumber: z.string().min(10).optional(),
// 'shuffle', located at `faker.helpers.shuffle`, is a function, but does not
// produce the appropriate return type to match `fakerFunction`
shuffle: z.string(),
// 'seed', located at `faker.mersenne.seed` is a function but will throw an error
// if it is called with the wrong parameter
seed: z.string(),
});
const mockData = generateMock(schema);
expect(typeof mockData.lorem).toEqual('string');
expect(typeof mockData.phoneNumber).toEqual('string');
expect(typeof mockData.shuffle).toEqual('string');
expect(typeof mockData.seed).toEqual('string');
});
it('Should manually mock string key names to set values', () => {
const schema = z.object({
uid: z.string().nonempty(),
theme: z.enum([`light`, `dark`]),
locked: z.string(),
email: z.string().email(),
camelCase: z.string(),
});
const stringMap = {
locked: () => `value set`,
email: () => `not a email anymore`,
camelCase: () => 'Exact case works',
};
const mockData = generateMock(schema, { stringMap });
expect(mockData.uid).toEqual(
expect.stringMatching(
/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/
)
);
expect(mockData.theme).toEqual(expect.stringMatching(/light|dark/));
expect(mockData.locked).toEqual('value set');
expect(mockData.email).toEqual(
expect.stringMatching('not a email anymore')
);
expect(mockData.camelCase).toEqual(stringMap.camelCase());
return;
});
it('Should manually mock string key names to set values when the validation has regex', () => {
const schema = z.object({
telephone: z.string().regex(/^\+[1-9]\d{1,14}$/)
});
const stringMap = {
telephone: () => '+919367788755',
};
const mockData = generateMock(schema, { stringMap });
expect(mockData.telephone).toEqual('+919367788755');
return;
});
it('should convert values produced by Faker to string when the schema type is string.', () => {
const schema = z.object({
number: z.string(),
boolean: z.string(),
date: z.string(),
});
const mockData = generateMock(schema);
expect(typeof mockData.number === 'string').toBeTruthy();
expect(typeof mockData.boolean === 'string').toBeTruthy();
expect(typeof mockData.date === 'string').toBeTruthy();
});
it("should support generating date strings via Faker for keys of 'date' and 'dateTime'.", () => {
const schema = z.object({
date: z.string(),
});
const mockData = generateMock(schema);
expect(new Date(mockData.date).getTime()).not.toBeNaN();
});
it('should correctly generate date strings for date validated strings', () => {
const schema = z.object({
dateString: z.string().datetime(),
});
const mockData = generateMock(schema);
expect(new Date(mockData.dateString).getTime()).not.toBeNaN();
});
describe('when handling min and max string lengths', () => {
const createSchema = (min: number, max: number) =>
z.object({
default: z.string().min(min).max(max),
email: z.string().min(min).max(max),
uuid: z.string().min(min).max(max),
url: z.string().min(min).max(max),
name: z.string().min(min).max(max),
color: z.string().min(min).max(max),
notFound: z.string().min(min).max(max),
});
it('should create mock strings that respect the specified min and max lengths (inclusive)', () => {
const min = 1;
const max = 5;
const mockData = generateMock(createSchema(min, max));
Object.values(mockData).forEach((val) => {
expect(val.length).toBeGreaterThanOrEqual(min);
expect(val.length).toBeLessThanOrEqual(max);
});
});
it('should respect the max length when the min is greater than the max', () => {
const min = 5;
const max = 2;
const mockData = generateMock(createSchema(min, max));
Object.values(mockData).forEach((val) => {
expect(val.length).toBeLessThanOrEqual(max);
});
});
it('should append extra string content to meet a minimum length', () => {
const min = 100;
const max = 100;
const mockData = generateMock(createSchema(min, max));
Object.values(mockData).forEach((val) => {
expect(val.length).toBeGreaterThanOrEqual(min);
expect(val.length).toBeLessThanOrEqual(max);
});
});
});
describe('when handling length property on string', () => {
const createSchema = (len: number) =>
z.object({
default: z.string().length(len),
});
it('should create mock strings that respect the specified length', () => {
const length = 33;
const mockData = generateMock(createSchema(length));
Object.values(mockData).forEach((val) => {
expect(val).toHaveLength(length);
});
});
});
it('should create mock dates that respect the specified min and max dates', () => {
const min = new Date('2022-01-01T00:00:00.000Z');
const max = new Date('2023-01-01T00:00:00.000Z');
const schema = z.object({
dateWithMin: z.date().min(min),
dateWithMax: z.date().max(max),
dateWithRange: z.date().min(min).max(max),
dateWithInvertedRange: z.date().min(max).max(min),
});
const mockData = generateMock(schema);
expect(mockData.dateWithMin.getTime()).toBeGreaterThanOrEqual(
min.getTime()
);
expect(mockData.dateWithMax.getTime()).toBeLessThanOrEqual(max.getTime());
expect(mockData.dateWithRange.getTime()).toBeGreaterThanOrEqual(
min.getTime()
);
expect(mockData.dateWithRange.getTime()).toBeLessThanOrEqual(max.getTime());
expect(mockData.dateWithInvertedRange).toBeUndefined();
});
describe('arrays', () => {
it('should mock an array without min or max', () => {
const schema = z.object({
data: z.array(z.string()),
});
const mockData = generateMock(schema);
expect(mockData.data.length).toBeTruthy();
expect(typeof mockData.data[0] === 'string');
});
it('should mock an array with a min, but no max', () => {
const schema = z.object({
data: z.array(z.string()).min(3),
});
const mockData = generateMock(schema);
expect(mockData.data.length).toBeGreaterThanOrEqual(3);
expect(typeof mockData.data[0] === 'string');
});
it('should mock an array with a max, but no min', () => {
const schema = z.object({
data: z.array(z.string()).max(1),
});
const mockData = generateMock(schema);
expect(mockData.data.length).toEqual(1);
expect(typeof mockData.data[0] === 'string');
});
it('should mock an array of length 10', () => {
const schema = z.object({
data: z.array(z.string()).length(10),
});
const mockData = generateMock(schema);
expect(mockData.data.length).toEqual(10);
expect(typeof mockData.data[0] === 'string');
});
it('should accurately mock a zero length array', () => {
const schema = z.object({
alwaysEmpty: z.array(z.string()).max(0),
});
const mockData = generateMock(schema);
expect(mockData.alwaysEmpty.length).toEqual(0);
});
it('should generate different value instances per array element', () => {
const schema = z.object({
data: z.array(z.date()).length(2),
});
const mockData = generateMock(schema);
expect(mockData.data.length).toEqual(2);
// even if the two dates represent the same instant in time,
// they should not be the same instance if we are mocking each
// array element separately.
expect(mockData.data[0] === mockData.data[1]).toBeFalsy();
});
});
describe('Sets', () => {
it('should mock an set without min or max', () => {
const schema = z.object({
data: z.set(z.string()),
});
const mockData = generateMock(schema);
expect(mockData.data.size).toBeTruthy();
expect(typeof [...mockData.data.values()][0] === 'string');
});
it('should mock an set with a min, but no max', () => {
const schema = z.object({
data: z.set(z.string()).min(3),
});
const mockData = generateMock(schema);
expect(mockData.data.size).toBeGreaterThanOrEqual(3);
expect(typeof [...mockData.data.values()][0] === 'string');
});
it('should mock an set with a max, but no min', () => {
const schema = z.object({
data: z.set(z.string()).max(1),
});
const mockData = generateMock(schema);
expect(mockData.data.size).toEqual(1);
expect(typeof [...mockData.data.values()][0] === 'string');
});
it('should mock an set of size 10', () => {
const setSchema = z.set(z.string()).size(10);
const schema = z.object({
data: setSchema,
});
expect(setSchema._def.maxSize?.value).toBe(10);
expect(setSchema._def.minSize?.value).toBe(10);
const mockData = generateMock(schema);
expect(mockData.data.size).toEqual(10);
expect(typeof [...mockData.data.values()][0] === 'string');
});
it('should accurately mock a zero size set', () => {
const schema = z.object({
alwaysEmpty: z.set(z.string()).max(0),
});
const mockData = generateMock(schema);
expect(mockData.alwaysEmpty.size).toEqual(0);
});
it('should generate different value instances per set element', () => {
const schema = z.object({
data: z.set(z.date()).size(2),
});
const mockData = generateMock(schema);
expect(mockData.data.size).toEqual(2);
const values = [...mockData.data.values()];
// even if the two dates represent the same instant in time,
// they should not be the same instance if we are mocking each
// set element separately.
expect(values[0] === values[1]).toBeFalsy();
});
});
it('should create Maps', () => {
const schema = z.map(z.string(), z.number());
const generated = generateMock(schema);
expect(generated.size).toBeGreaterThan(0);
const entries = [...generated.entries()];
entries.forEach(([k, v]) => {
expect(k).toBeTruthy();
expect(v).toBeTruthy();
});
});
describe('backup mocks', () => {
const notUndefined = () => 'not undefined';
it('should use a user provided generator when a generator for the schema type cannot be found', () => {
// undefined is used because we have no reason to create a generator for it because the net result
// will be undefined.
const mock = generateMock(z.undefined(), {
backupMocks: { ZodUndefined: notUndefined },
});
expect(mock).toEqual(notUndefined());
});
it('should use a user provided generator when a generator takes 2 arguments', () => {
// Given
const custom = z.custom<Date>((val) => val instanceof Date);
const anyDate = () => '2023-01-01T00:00:00.000Z';
const zodCustomBackupMock = (ref: z.ZodType): string | void => {
if (ref === (custom as z.ZodEffects<z.ZodAny>)._def.schema) {
return anyDate();
}
};
// When
const mock = generateMock(custom, {
backupMocks: { ZodAny: zodCustomBackupMock },
});
// Then
expect(mock).toEqual(anyDate());
// When
const mock2 = generateMock(
z.custom(() => false),
{
backupMocks: { ZodAny: zodCustomBackupMock },
}
);
// Then
expect(mock2).toBeUndefined();
});
it('should work with objects and arrays', () => {
const schema = z.object({
data: z.array(z.undefined()).length(1),
});
const mock = generateMock(schema, {
backupMocks: { ZodUndefined: notUndefined },
});
expect(mock.data[0]).toEqual(notUndefined());
});
it('should work with the README example', () => {
const schema = z.object({
anyVal: z.any(),
});
const mockData = generateMock(schema, {
backupMocks: {
ZodAny: () => 'any value',
},
});
expect(mockData.anyVal).toEqual('any value');
});
});
it('throws an error when configured to if we have not implemented the type mapping', () => {
expect(() =>
generateMock(z.any(), { throwOnUnknownType: true })
).toThrowError(ZodMockError);
});
// TODO: enable tests as their test types are implemented
xdescribe('missing types', () => {
it('ZodAny', () => {
expect(generateMock(z.any())).toBeTruthy();
});
it('ZodUnknown', () => {
expect(generateMock(z.unknown())).toBeTruthy();
});
});
it('ZodDefault', () => {
const value = generateMock(z.string().default('a'));
expect(value).toBeTruthy();
expect(typeof value).toBe('string');
});
it('ZodNativeEnum', () => {
enum NativeEnum {
a = 1,
b = 2,
}
const first = generateMock(z.nativeEnum(NativeEnum));
expect(first === 1 || first === 2);
const ConstAssertionEnum = {
a: 1,
b: 2,
} as const;
const second = generateMock(z.nativeEnum(ConstAssertionEnum));
expect(second === 1 || second === 2);
});
it('ZodFunction', () => {
const func = generateMock(z.function(z.tuple([]), z.string()));
expect(func).toBeTruthy();
expect(typeof func()).toBe('string');
});
it('ZodIntersection', () => {
const Person = z.object({
name: z.string(),
});
const Employee = z.object({
role: z.string(),
});
const EmployedPerson = z.intersection(Person, Employee);
const generated = generateMock(EmployedPerson);
expect(generated).toBeTruthy();
expect(generated.name).toBeTruthy();
expect(generated.role).toBeTruthy();
});
it('ZodPromise', async () => {
const promise = generateMock(z.promise(z.string()));
expect(promise).toBeTruthy();
const result = await promise;
expect(typeof result).toBe('string');
});
describe('ZodTuple', () => {
it('basic tuple', () => {
const generated = generateMock(
z.tuple([z.number(), z.string(), z.boolean()])
);
expect(generated).toBeTruthy();
const [num, str, bool] = generated;
expect(typeof num).toBe('number');
expect(typeof str).toBe('string');
expect(typeof bool).toBe('boolean');
});
it('tuple with Rest args', () => {
const generated = generateMock(
z.tuple([z.number(), z.boolean()]).rest(z.string())
);
expect(generated).toBeTruthy();
const [num, bool, ...rest] = generated;
expect(typeof num).toBe('number');
expect(typeof bool).toBe('boolean');
expect(rest.length).toBeGreaterThan(0);
for (const item of rest) {
expect(typeof item).toBe('string');
}
});
});
it('ZodUnion', () => {
expect(generateMock(z.union([z.number(), z.string()]))).toBeTruthy();
});
it(`Avoid depreciations in strings`, () => {
const warn = jest
.spyOn(console, 'warn')
.mockImplementation(() => undefined);
generateMock(
z.object({
image: z.string(),
number: z.string(),
float: z.string(),
uuid: z.string(),
boolean: z.string(),
hexaDecimal: z.string(),
})
);
expect(warn).toBeCalledTimes(0);
});
it('should generate strings from regex', () => {
const regResult = generateMock(
z.object({
data: z.string().regex(/^[A-Z0-9+_.-]+@[A-Z0-9.-]+$/),
})
);
expect(regResult.data).toMatch(/^[A-Z0-9+_.-]+@[A-Z0-9.-]+$/);
});
it('should handle complex unions', () => {
const result = generateMock(z.object({ date: z.date() }));
expect(result.date).toBeInstanceOf(Date);
// Date
const variousTypes = z.union([
z
.string()
.min(1)
.max(100)
.transform((v) => v.length),
z.number().gt(1).lt(100),
z
.string()
.regex(/^(100|[1-9][0-9]?)$/)
.transform((v) => parseInt(v)),
]);
const TransformItem = z.object({
id: z.string().nonempty({ message: 'Missing ID' }),
name: z.string().optional(),
items: variousTypes,
});
const transformResult = generateMock(TransformItem);
expect(transformResult.items).toBeGreaterThan(0);
expect(transformResult.items).toBeLessThan(101);
});
it('should handle discriminated unions', () => {
const FirstType = z.object({
hasEmail: z.literal(false),
userName: z.string(),
});
const SecondType = z.object({
hasEmail: z.literal(true),
email: z.string(),
});
const Union = z.discriminatedUnion('hasEmail', [FirstType, SecondType]);
const result = generateMock(Union);
expect(result).toBeDefined();
if (result.hasEmail) {
expect(result.email).toBeTruthy();
} else {
expect(result.userName).toBeTruthy();
}
});
it('should handle branded types', () => {
const Branded = z.string().brand<'__brand'>();
const result = generateMock(Branded);
expect(result).toBeTruthy();
});
it('ZodVoid', () => {
expect(generateMock(z.void())).toBeUndefined();
});
it('ZodNull', () => {
expect(generateMock(z.null())).toBeNull();
});
it('ZodNaN', () => {
expect(generateMock(z.nan())).toBeNaN();
});
it('ZodUndefined', () => {
expect(generateMock(z.undefined())).toBeUndefined();
});
it('ZodLazy', () => {
expect(generateMock(z.lazy(() => z.string()))).toBeTruthy();
});
it('Options seed value will return the same random numbers', () => {
const schema = z.object({
name: z.string(),
age: z.number(),
});
const seed = 123;
const first = generateMock(schema, { seed });
const second = generateMock(schema, { seed });
expect(first).toEqual(second);
});
it('Options seed value will return the same union & enum members', () => {
enum NativeEnum {
a = 1,
b = 2,
}
const schema = z.object({
theme: z.enum([`light`, `dark`]),
nativeEnum: z.nativeEnum(NativeEnum),
union: z.union([z.literal('a'), z.literal('b')]),
discriminatedUnion: z.discriminatedUnion('discriminator', [
z.object({ discriminator: z.literal('a'), a: z.boolean() }),
z.object({ discriminator: z.literal('b'), b: z.string() }),
]),
});
const seed = 123;
const first = generateMock(schema, { seed });
const second = generateMock(schema, { seed });
expect(first).toEqual(second);
});
it('Options seed value will return the same generated regex values', () => {
const schema = z.object({
data: z.string().regex(/^[A-Z0-9+_.-]+@[A-Z0-9.-]+$/),
});
const seed = 123;
const first = generateMock(schema, { seed });
const second = generateMock(schema, { seed });
expect(first).toEqual(second);
});
it('Can use my own version of faker', () => {
enum NativeEnum {
a = 1,
b = 2,
}
const schema = z.object({
uid: z.string().nonempty(),
theme: z.enum([`light`, `dark`]),
name: z.string(),
firstName: z.string(),
email: z.string().email().optional(),
phoneNumber: z.string().min(10).optional(),
avatar: z.string().url().optional(),
jobTitle: z.string().optional(),
otherUserEmails: z.array(z.string().email()),
stringArrays: z.array(z.string()),
stringLength: z.string().transform((val) => val.length),
numberCount: z.number().transform((item) => `total value = ${item}`),
age: z.number().min(18).max(120),
record: z.record(z.string(), z.number()),
nativeEnum: z.nativeEnum(NativeEnum),
set: z.set(z.string()),
map: z.map(z.string(), z.number()),
discriminatedUnion: z.discriminatedUnion('discriminator', [
z.object({ discriminator: z.literal('a'), a: z.boolean() }),
z.object({ discriminator: z.literal('b'), b: z.string() }),
]),
dateWithMin: z.date().min(new Date('2023-01-01T00:00:00Z')),
});
faker.seed(3);
const first = generateMock(schema, { faker });
faker.seed(3);
const second = generateMock(schema, { faker });
const third = generateMock(schema);
expect(first).toEqual(second);
expect(first).not.toEqual(third);
});
it(`Will mock sub objections properly`, () => {
const airline = z.object({
flightNumber: z.string(),
departure: z.object({
airport: z.string(),
time: z.date(),
}),
arrival: z.object({
airport: z.string(),
time: z.date(),
}),
});
const flight = z.object({
operating_airline: airline,
marketing_airline: airline,
});
const mockedFlight = generateMock(flight, {
stringMap: {
airport: () => faker.airline.airport().iataCode,
},
});
expect(mockedFlight.operating_airline.departure.airport.length).toEqual(3);
expect(mockedFlight.operating_airline.arrival.airport.length).toEqual(3);
expect(mockedFlight.marketing_airline.departure.airport.length).toEqual(3);
expect(mockedFlight.marketing_airline.arrival.airport.length).toEqual(3);
expect(mockedFlight.operating_airline.departure.time).toBeInstanceOf(Date);
expect(mockedFlight.operating_airline.flightNumber.length).toBeLessThan(5);
});
describe('mockeryMapper', () => {
const quota = z.object({
id: z.number(),
created: z.date(),
territoryName: z.string(),
enabled: z.boolean(),
});
const mockeryMapper = (
keyName: string,
fakerInstance: Faker
): FakerFunction | undefined => {
const keyToFnMap: Record<string, FakerFunction> = {
id: () => fakerInstance.number.int({ min: 3, max: 22 }),
enabled: () => fakerInstance.datatype.boolean({ probability: 1 }),
territoryName: () => fakerInstance.string.fromCharacters('abcdef', 20),
created: () => fakerInstance.date.past(),
};
return keyName && keyName.toLowerCase() in keyToFnMap
? keyToFnMap[keyName.toLowerCase() as never]
: undefined;
};
// generate multiple records to ensure consistency
const mockedQuotas = generateMock(quota.array().length(10), {
mockeryMapper,
});
describe.each(mockedQuotas)(
'%#. quota with id $id mock data unit tests',
(mockedQuota, index) => {
it(`uses the id faker function in the mockeryMapper to generate ${mockedQuota.id}`, () => {
// the value should always be in the range [3, 22] as pert hge mockery mapper function
expect(mockedQuota.id).toBeGreaterThanOrEqual(3);
expect(mockedQuota.id).toBeLessThanOrEqual(22);
});
it(`uses the enabled faker function in the mockeryMapper to generate ${mockedQuota.enabled}`, () => {
// the value should always be true as per the mockery mapper function
expect(mockedQuota.enabled).toBe(true);
});
it(`uses the created faker function in the mockeryMapper to generate ${mockedQuota.created.toISOString()}`, () => {
// the date should always be in the past as per the mockery mapper function
expect(mockedQuota.created).toBeInstanceOf(Date);
expect(mockedQuota.created.getTime()).toBeLessThan(
new Date().getTime()
);
});
}
);
});
});