This repository has been archived by the owner on Jul 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.test.ts
401 lines (348 loc) · 10.9 KB
/
index.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
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
import { describe, expect, it, expectTypeOf } from 'vitest';
import { z } from 'zod';
import { deserialize, serialize, serializable, validateWith, validateSetWith } from './index.js';
const AddressSchema = z.object({
details: z.object({ city: z.string(), zipCode: z.string() })
});
class Address {
public readonly SCHEMA = AddressSchema;
@serializable('details')
accessor details: { city: string; zipCode: string };
constructor(parameters: z.infer<Address['SCHEMA']>) {
this.details = parameters.details;
}
public get city() {
return this.details.city;
}
public get zipCode() {
return this.details.zipCode;
}
}
const PersonSchema = z.object({
address: z.instanceof(Address),
name: z.string()
});
class Person {
public readonly SCHEMA = PersonSchema;
@serializable('address', Address)
accessor address: Address;
@serializable('name')
accessor name: string;
constructor(params: z.infer<Person['SCHEMA']>) {
this.address = params.address;
this.name = params.name;
}
}
const CompanySchema = z.object({
people: z.array(z.instanceof(Person))
});
class Company {
public readonly SCHEMA = CompanySchema;
@serializable('people', {
doSerialize: (a) => a.map((i) => serialize(i)),
doDeserialize: (a) => a.map((i) => deserialize(i, Person))
})
accessor people: Person[];
constructor(params: z.infer<Company['SCHEMA']>) {
this.people = params.people;
}
}
const InternationalAddressSchema = AddressSchema.extend({
country: z.string()
});
class InternationalAddress extends Address {
public readonly SCHEMA = InternationalAddressSchema;
@serializable('country')
accessor country: string;
constructor(parameters: z.infer<InternationalAddress['SCHEMA']>) {
super(parameters);
this.country = parameters.country;
}
}
const baseDirectorySchema = z.object({
name: z.string()
});
type DirectorySchema = z.infer<typeof baseDirectorySchema> & {
subdirectories: Directory[];
};
class Directory {
public readonly SCHEMA: z.ZodType<DirectorySchema> = baseDirectorySchema.extend({
subdirectories: z.array(z.instanceof(Directory))
});
@serializable('subdirectories', {
doSerialize: (a) => a.map((i) => serialize(i)),
doDeserialize: (a) => a.map((i) => deserialize(i, Directory))
})
accessor subdirectories: Directory[];
@serializable('name')
accessor name: string;
constructor(parameters: z.infer<Directory['SCHEMA']>) {
this.subdirectories = parameters.subdirectories;
this.name = parameters.name;
}
}
class WithOptional {
public readonly SCHEMA = z.object({
title: z.string().optional()
});
@serializable('title')
readonly title?: string;
constructor(params: z.infer<WithOptional['SCHEMA']>) {
this.title = params.title;
}
}
describe('serializable', () => {
const addressObj = { details: { city: 'City', zipCode: '12345' } };
const personObj = {
name: 'Joe Shmo',
address: addressObj
};
const address = new Address(addressObj);
const person = new Person({ address, name: 'Joe Shmo' });
const company = new Company({ people: [person] });
describe('serialize', () => {
it('serializes a basic class', () => {
const serialized = serialize(address);
expect(serialized).toEqual({ details: { city: 'City', zipCode: '12345' } });
expectTypeOf(serialized).toEqualTypeOf<{
details: {
city: string;
zipCode: string;
};
}>();
});
it('supports optional attributes', () => {
const thing = new WithOptional({});
const serialized = serialize(thing);
expect(serialized).toEqual({
title: undefined
});
expectTypeOf(serialized).toEqualTypeOf<{
title?: string;
}>();
});
it('recursively serializes', () => {
const serialized = serialize(person);
expect(serialized).toEqual(personObj);
expectTypeOf(serialized).toEqualTypeOf<{
address: {
details: {
city: string;
zipCode: string;
};
};
name: string;
}>();
});
it('serializes collections', () => {
const serialized = serialize(company);
expect(serialized).toEqual({
people: [personObj]
});
expectTypeOf(serialized).toEqualTypeOf<{
people: {
address: {
details: {
city: string;
zipCode: string;
};
};
name: string;
}[];
}>();
});
it('uses the key name defined in the schema, even when it diverges from the accessor name', () => {
const ExampleSchema = z.object({
foo: z.string()
});
class Example {
public readonly SCHEMA = ExampleSchema;
@serializable('foo')
accessor bar: string = 'hello';
}
const instance = new Example();
const serialized = serialize(instance);
expect(serialized).toEqual({ foo: 'hello' });
});
it('serializes subclasses', () => {
const instance = new InternationalAddress({
details: { city: 'City', zipCode: '12345' },
country: 'United States'
});
expect(serialize(instance)).toEqual({
country: 'United States',
...addressObj
});
});
it('allows subclasses to override serializables', () => {
class Dep {
public readonly SCHEMA = z.object({
foo: z.string()
});
@serializable('foo')
accessor foo: string = 'foo';
}
class DepChild extends Dep {
accessor foo: string = 'bar';
}
class Example {
public readonly SCHEMA = z.object({
dep: z.instanceof(Dep)
});
protected accessor _dep: Dep;
@serializable('dep', Dep)
get dep() {
return this._dep;
}
constructor(params: z.infer<Example['SCHEMA']>) {
this._dep = params.dep;
}
}
class ExampleChild extends Example {
public readonly SCHEMA = z.object({
dep: z.instanceof(DepChild)
});
@serializable('dep', DepChild)
get dep() {
return this._dep;
}
}
const child = new ExampleChild({ dep: new DepChild() });
const serialized = serialize(child);
const deserialized = deserialize(serialized, ExampleChild);
expect(deserialized.dep).toBeInstanceOf(DepChild);
expect(deserialized.dep.foo).toEqual('bar');
});
it('serializes objects with recursive schemas', () => {
const directory = new Directory({
name: 'folder-a',
subdirectories: [new Directory({ name: 'folder-b', subdirectories: [] })]
});
const serialized = serialize(directory);
expect(serialized).toEqual({
subdirectories: [{ subdirectories: [], name: 'folder-b' }],
name: 'folder-a'
});
});
describe('strict', () => {
it('ensures all keys in the SCHEMA have been serialized', () => {
class Example {
public readonly SCHEMA = z.object({
foo: z.string(),
bar: z.string()
});
@serializable('foo')
accessor foo: string = 'foo';
accessor _bar: string = 'bar';
}
class ExampleFixed extends Example {
@serializable('bar')
get bar() {
return super._bar;
}
}
expect(() => {
serialize(new Example(), { strict: true });
}).toThrow('missing keys: bar');
expect(() => {
serialize(new ExampleFixed(), { strict: true });
}).not.toThrow();
});
});
});
describe('deserialize', () => {
it('deserializes a basic class', () => {
const deserialized = deserialize(addressObj, Address);
expect(deserialized.city).toEqual('City');
expect(deserialized.zipCode).toEqual('12345');
});
it('supports optional attributes', () => {
expect(deserialize({}, WithOptional).title).toBeUndefined();
expect(deserialize({ title: 'hello' }, WithOptional).title).toEqual('hello');
});
it('recursively deserializes', () => {
const deserialized = deserialize(personObj, Person);
expect(deserialized.name).toEqual(person.name);
expect(deserialized.address.city).toEqual(person.address.city);
expect(deserialized.address.zipCode).toEqual(person.address.zipCode);
});
it('deserializes collections', () => {
const deserialized = deserialize({ people: [personObj] }, Company);
expect(deserialized.people).toEqual([person]);
});
it('uses the key name defined in the schema, even when it diverges from the accessor name', () => {
const ExampleSchema = z.object({
foo: z.string()
});
class Example {
public readonly SCHEMA = ExampleSchema;
@serializable('foo')
accessor bar: string;
constructor(params: z.infer<Example['SCHEMA']>) {
this.bar = params.foo;
}
}
const instance = new Example({ foo: 'hello' });
const deserialized = deserialize(serialize(instance), Example);
expect(instance.bar).toEqual(deserialized.bar);
});
it('deserializes subclasses', () => {
const serialized = {
country: 'United States',
...addressObj
};
const intlAddress = deserialize(serialized, InternationalAddress);
expect(intlAddress.country).toEqual('United States');
expect(intlAddress.city).toEqual('City');
expect(intlAddress.zipCode).toEqual('12345');
});
it('deserializes objects with recursive schemas', () => {
const serialized = {
subdirectories: [{ subdirectories: [], name: 'folder-b' }],
name: 'folder-a'
};
const directory = deserialize(serialized, Directory);
expect(directory.name).toEqual('folder-a');
expect(directory.subdirectories[0].name).toEqual('folder-b');
});
});
describe('strict', () => {
it('throws an error when it deserializes an incorrect shape', () => {
expect(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
deserialize({ ...personObj, name: undefined } as any, Person, { strict: true });
}).toThrow('invalid_type');
});
});
});
describe('validateWith', () => {
class Email {
@validateWith(z.string().email())
accessor address: string;
#foo: string = '';
@validateSetWith(z.string().min(4))
set foo(s: string) {
this.#foo = s;
}
constructor(address: string) {
this.address = address;
}
}
it('throws an error on invalid email address', () => {
expect(() => {
new Email('invalid');
}).toThrow('Invalid email');
});
it('throws an error on setting foo with a string shorter than 4 characters', () => {
const email = new Email('[email protected]');
expect(() => {
email.foo = 's';
}).toThrow('too_small');
});
it('allows setting foo with a string of at least 4 characters', () => {
const email = new Email('[email protected]');
expect(() => {
email.foo = 'asdjkj';
}).not.toThrow();
});
});