-
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathEntityMixin.test.ts
More file actions
1322 lines (1224 loc) · 36.7 KB
/
EntityMixin.test.ts
File metadata and controls
1322 lines (1224 loc) · 36.7 KB
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// eslint-env jest
import { normalize, INVALID } from '@data-client/normalizr';
import { denormalize as plainDenormalize } from '@data-client/normalizr';
import { denormalize as immDenormalize } from '@data-client/normalizr/imm';
import { Temporal } from 'temporal-polyfill';
import { SimpleMemoCache, fromJSEntities } from './denormalize';
import { schema, EntityMixin, Values } from '../..';
let dateSpy: jest.Spied<any>;
beforeAll(() => {
dateSpy = jest
.spyOn(global.Date, 'now')
.mockImplementation(() => new Date('2019-05-14T11:01:58.135Z').valueOf());
});
afterAll(() => {
dateSpy.mockRestore();
});
const values = <T extends { [k: string]: any }>(obj: T) =>
Object.keys(obj).map(key => obj[key]);
class TacoData {
id = '';
name = '';
alias: string | undefined = undefined;
}
class Tacos extends EntityMixin(TacoData) {}
class ArticleData {
readonly id: string = '';
readonly title: string = '';
readonly author: string = '';
readonly content: string = '';
}
class ArticleEntity extends EntityMixin(ArticleData) {}
class OptionalData {
readonly id: string = '';
readonly article: ArticleEntity | null = null;
readonly requiredArticle = ArticleEntity.fromJS();
readonly nextPage: string = '';
}
class WithOptional extends EntityMixin(OptionalData, {
schema: {
article: ArticleEntity,
requiredArticle: ArticleEntity,
},
}) {}
class IDData {
id = '';
}
describe(`${schema.Entity.name} construction`, () => {
describe('pk', () => {
it('should use provided pk if part of class', () => {
class MyData {
username = '';
title = '';
pk() {
return this.username;
}
}
const MyEntity = EntityMixin(MyData);
expect(MyEntity.pk({ username: 'bob' })).toBe('bob');
const entity = MyEntity.fromJS({ username: 'bob' });
expect(entity.pk()).toBe('bob');
// @ts-expect-error
entity.lksdfl;
});
it('should use pk overide in Entity', () => {
class MyData {
username = '';
title = '';
pk() {
return this.username;
}
}
class MyEntity extends EntityMixin(MyData) {
pk() {
return this.title;
}
}
expect(MyEntity.pk({ title: 'hi' })).toBe('hi');
expect(MyEntity.fromJS({ title: 'hi' }).pk()).toBe('hi');
});
it('should use pk overide in Entity when base is set via options', () => {
class MyData {
username = '';
title = '';
}
class MyEntity extends EntityMixin(MyData, { pk: 'username' }) {
pk() {
return this.title;
}
}
expect(MyEntity.pk({ title: 'hi' })).toBe('hi');
expect(MyEntity.fromJS({ title: 'hi' }).pk()).toBe('hi');
});
it('should use pk field names', () => {
class MyData {
username = '';
title = '';
}
class MyEntity extends EntityMixin(MyData, { pk: 'username' }) {}
expect(MyEntity.pk({ username: 'bob' })).toBe('bob');
expect(MyEntity.fromJS({ username: 'bob' }).pk()).toBe('bob');
});
it('should use pk function option', () => {
class MyData {
username = '';
title = '';
}
class MyEntity extends EntityMixin(MyData, {
pk(v) {
//@ts-expect-error
v.sdlfkjsd;
return v.username;
},
}) {}
expect(MyEntity.pk({ username: 'bob' })).toBe('bob');
expect(MyEntity.fromJS({ username: 'bob' }).pk()).toBe('bob');
});
it('should fail with bad pk field name', () => {
class MyData {
username = '';
title = '';
}
// @ts-expect-error
class MyEntity extends EntityMixin(MyData, { pk: 'id' }) {}
// @ts-expect-error
expect(MyEntity.pk({ username: 'bob' })).toBeUndefined();
// @ts-expect-error
expect(MyEntity.fromJS({ username: 'bob' }).pk()).toBeUndefined();
});
it('should fail with no id and pk unspecified', () => {
class MyData {
username = '';
title = '';
}
// @ts-expect-error
class MyEntity extends EntityMixin(MyData) {}
// @ts-expect-error
expect(MyEntity.pk({ username: 'bob' })).toBeUndefined();
// @ts-expect-error
expect(MyEntity.fromJS({ username: 'bob' }).pk()).toBeUndefined();
expect(() =>
normalize(MyEntity, { username: 'bob' }),
).toThrowErrorMatchingSnapshot();
});
it('should use id field if no pk specified', () => {
class MyData {
id = '';
username = '';
title = '';
}
class MyEntity extends EntityMixin(MyData) {}
expect(MyEntity.pk({ id: '5' })).toBe('5');
expect(MyEntity.fromJS({ id: '5' }).pk()).toBe('5');
});
});
describe('key', () => {
it('should use class name with no key in options', () => {
class MyData {
id = '';
username = '';
title = '';
}
const MyEntity = EntityMixin(MyData);
expect(MyEntity.key).toBe('MyData');
});
it('should error with no discernable name', () => {
const MyEntity = EntityMixin(
class {
id = '';
username = '';
title = '';
},
);
expect(() => MyEntity.key).toThrowErrorMatchingInlineSnapshot(`
"Entity classes without a name must define \`static key\`
See: https://dataclient.io/rest/api/Entity#key"
`);
});
it('should use entity class name with no key in options', () => {
class MyData {
id = '';
username = '';
title = '';
}
class MyEntity extends EntityMixin(MyData) {}
expect(MyEntity.key).toBe('MyEntity');
});
it('should use key in options', () => {
class MyData {
id = '';
username = '';
title = '';
}
const MyEntity = EntityMixin(MyData, { key: 'MYKEY' });
expect(MyEntity.key).toBe('MYKEY');
class MyEntity2 extends EntityMixin(MyData, { key: 'MYKEY' }) {}
expect(MyEntity2.key).toBe('MYKEY');
});
it('should use static key in base class', () => {
class MyData {
id = '';
username = '';
title = '';
static key = 'MYKEY';
}
const MyEntity = EntityMixin(MyData);
expect(MyEntity.key).toBe('MYKEY');
});
it('should have options.key override base class', () => {
class MyData {
id = '';
username = '';
title = '';
static key = 'MYKEY';
}
const MyEntity = EntityMixin(MyData, { key: 'OVERRIDE' });
expect(MyEntity.key).toBe('OVERRIDE');
});
it('static key in Entity should override options', () => {
class MyData {
id = '';
username = '';
title = '';
}
class MyEntity extends EntityMixin(MyData, { key: 'OPTIONSKEY' }) {
static key = 'STATICKEY';
}
expect(MyEntity.key).toBe('STATICKEY');
});
});
describe('schema', () => {
it('options.schema should set schema', () => {
class MyData {
id = '';
username = '';
title = '';
createdAt = Temporal.Instant.fromEpochMilliseconds(0);
}
class MyEntity extends EntityMixin(MyData, {
schema: { createdAt: Temporal.Instant.from },
}) {}
expect(MyEntity.schema).toEqual({ createdAt: Temporal.Instant.from });
});
it('options.schema should override base schema', () => {
class MyData {
id = '';
username = '';
title = '';
createdAt = Temporal.Instant.fromEpochMilliseconds(0);
static schema = {
user: Temporal.Instant.from,
};
}
class MyEntity extends EntityMixin(MyData, {
schema: { createdAt: Temporal.Instant.from },
}) {}
expect(MyEntity.schema).toEqual({ createdAt: Temporal.Instant.from });
});
it('static schema in base should be used', () => {
class MyData {
id = '';
username = '';
title = '';
createdAt = Temporal.Instant.fromEpochMilliseconds(0);
static schema = {
createdAt: Temporal.Instant.from,
};
}
class MyEntity extends EntityMixin(MyData) {}
expect(MyEntity.schema).toEqual({ createdAt: Temporal.Instant.from });
});
it('static schema in Entity should override options', () => {
class MyData {
id = '';
username = '';
title = '';
createdAt = Temporal.Instant.fromEpochMilliseconds(0);
}
class MyEntity extends EntityMixin(MyData, {
schema: { createdAt: Temporal.Instant.from },
}) {
static schema = {
user: Temporal.Instant.from,
};
}
expect(MyEntity.schema).toEqual({ user: Temporal.Instant.from });
});
});
});
describe(`${schema.Entity.name} normalization`, () => {
let warnSpy: jest.Spied<typeof console.warn>;
afterEach(() => {
warnSpy.mockRestore();
});
beforeEach(() => {
warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
});
test('normalizes an entity', () => {
class MyEntity extends EntityMixin(IDData) {}
expect(normalize(MyEntity, { id: '1' })).toMatchSnapshot();
});
test('normalizes already processed entities', () => {
class MyEntity extends EntityMixin(IDData) {}
class MyData {
id = '';
title = '';
nest = MyEntity.fromJS();
}
class Nested extends EntityMixin(MyData, {
schema: {
nest: MyEntity,
},
}) {}
expect(normalize(new schema.Array(MyEntity), ['1'])).toMatchSnapshot();
expect(
normalize(new schema.Object({ data: MyEntity }), { data: '1' }),
).toMatchSnapshot();
expect(
normalize(Nested, { title: 'hi', id: '5', nest: '10' }),
).toMatchSnapshot();
});
test('normalizes does not change value when shouldUpdate() returns false', () => {
class MyData {
id = '';
title = '';
}
class MyEntity extends EntityMixin(MyData) {
static shouldUpdate() {
return false;
}
}
const { entities, entitiesMeta } = normalize(MyEntity, {
id: '1',
title: 'hi',
});
const secondEntities = normalize(
MyEntity,
{ id: '1', title: 'second' },
[],
{ entities, entitiesMeta, indexes: {} },
).entities;
expect(entities.MyEntity['1']).toBeDefined();
expect(entities.MyEntity['1']).toBe(secondEntities.MyEntity['1']);
});
it('should throw a custom error if data does not include pk', () => {
class MyData {
name = '';
secondthing = '';
}
const MyEntity = EntityMixin(MyData, { pk: 'name' });
function normalizeBad() {
normalize(MyEntity, { secondthing: 'hi' });
}
expect(normalizeBad).toThrowErrorMatchingSnapshot();
// @ts-expect-error
EntityMixin(MyData, { pk: 'sdfasd' });
});
it('should not throw if schema key is missing from Entity', () => {
class MyData {
name = '';
secondthing = '';
}
// @ts-expect-error
const MyEntity = EntityMixin(MyData, {
pk: 'name',
schema: {
blarb: Temporal.Instant.from,
},
});
expect(
normalize(MyEntity, { name: 'bob', secondthing: 'hi' }),
).toMatchSnapshot();
});
it('should handle optional schema entries Entity', () => {
class MyData {
readonly name: string = '';
readonly secondthing: string = '';
readonly blarb: Date | undefined = undefined;
}
class MyEntity extends EntityMixin(MyData, {
pk: 'name',
schema: {
blarb: Temporal.Instant.from,
},
}) {}
expect(normalize(MyEntity, { name: 'bob', secondthing: 'hi' }))
.toMatchInlineSnapshot(`
{
"entities": {
"MyEntity": {
"bob": {
"name": "bob",
"secondthing": "hi",
},
},
},
"entitiesMeta": {
"MyEntity": {
"bob": {
"date": 1557831718135,
"expiresAt": Infinity,
"fetchedAt": 0,
},
},
},
"indexes": {},
"result": "bob",
}
`);
});
it('should throw a custom error if data loads with no matching props', () => {
class MyData {
name = '';
secondthing = '';
}
const MyEntity = EntityMixin(MyData, { pk: 'name' });
function normalizeBad() {
normalize(MyEntity, {});
}
expect(normalizeBad).toThrowErrorMatchingSnapshot();
});
it('should throw a custom error loads with array', () => {
class MyData {
name = '';
secondthing = '';
}
const MyEntity = EntityMixin(MyData, { pk: 'name' });
function normalizeBad() {
normalize(MyEntity, [
{ name: 'hi', secondthing: 'ho' },
{ name: 'hi', secondthing: 'ho' },
{ name: 'hi', secondthing: 'ho' },
]);
}
expect(normalizeBad).toThrowErrorMatchingSnapshot();
});
it('should error if no matching keys are found', () => {
class MyData {
readonly name: string = '';
}
// @ts-expect-error
class MyEntity extends EntityMixin(MyData, { pk: 'e' }) {}
expect(() =>
normalize(MyEntity, {
name: 0,
}),
).toThrowErrorMatchingSnapshot();
});
it('should allow many unexpected as long as none are missing', () => {
class MyData {
readonly name: string = '';
readonly a: string = '';
}
class MyEntity extends EntityMixin(MyData, { pk: 'name' }) {}
expect(
normalize(MyEntity, {
name: 'hi',
a: 'a',
b: 'b',
c: 'c',
d: 'e',
e: 0,
f: 0,
g: 0,
h: 0,
i: 0,
j: 0,
k: 0,
l: 0,
m: 0,
n: 0,
o: 0,
p: 0,
q: 0,
r: 0,
s: 0,
t: 0,
u: 0,
}),
).toMatchSnapshot();
expect(warnSpy.mock.calls.length).toBe(0);
});
it('should not expect getters returned', () => {
class MyData {
readonly name: string = '';
get other() {
return this.name + 5;
}
get another() {
return 'another';
}
get yetAnother() {
return 'another2';
}
}
class MyEntity extends EntityMixin(MyData, { pk: 'name' }) {}
function normalizeBad() {
normalize(MyEntity, { name: 'bob' });
}
expect(normalizeBad).not.toThrow();
expect(warnSpy.mock.calls.length).toBe(0);
});
it('should throw a custom error if data loads with string', () => {
class MyData {
readonly name: string = '';
readonly secondthing: string = '';
readonly thirdthing: number = 0;
pk() {
return this.name;
}
}
const MyEntity = EntityMixin(MyData);
function normalizeBad() {
normalize({ data: MyEntity }, 'hibho');
}
expect(normalizeBad).toThrowErrorMatchingSnapshot();
});
describe('key', () => {
test('key name must be a string', () => {
class MyData {
id = '';
}
// @ts-expect-error
class MyEntity extends EntityMixin(MyData) {
static get key() {
return 42;
}
}
});
});
describe('pk()', () => {
test('can use a custom pk() string', () => {
class User {
readonly idStr: string = '';
readonly name: string = '';
}
const UserEntity = EntityMixin(User, { pk: 'idStr' });
expect(
normalize(UserEntity, { idStr: '134351', name: 'Kathy' }),
).toMatchSnapshot();
});
test('can normalize entity IDs based on their object key', () => {
class User {
readonly name: string = '';
}
const UserEntity = EntityMixin(User, {
pk(value, parent, key) {
return key;
},
});
const inputSchema = new Values({ users: UserEntity }, () => 'users');
expect(
normalize(inputSchema, {
'4': { name: 'taco' },
'56': { name: 'burrito' },
}),
).toMatchSnapshot();
});
test("can build the entity's ID from the parent object", () => {
class User {
readonly id: string = '';
readonly name: string = '';
}
const UserEntity = EntityMixin(User, {
pk(value, parent, key) {
return `${parent.name}-${key}-${value.id}`;
},
});
const inputSchema = new schema.Object({ user: UserEntity });
expect(
normalize(inputSchema, {
name: 'tacos',
user: { id: '4', name: 'Jimmy' },
}),
).toMatchSnapshot();
});
});
describe('mergeStrategy', () => {
test('defaults to plain merging', () => {
expect(
normalize(
[Tacos],
[
{ id: '1', name: 'foo' },
{ id: '1', name: 'bar', alias: 'bar' },
],
),
).toMatchSnapshot();
});
test('can use a custom merging strategy', () => {
class MergeTaco extends Tacos {
static merge(existing: any, incoming: any) {
const props = Object.assign({}, existing, incoming, {
name: (existing as MergeTaco).name,
});
return this.fromJS(props);
}
}
expect(
normalize(
[MergeTaco],
[
{ id: '1', name: 'foo' },
{ id: '1', name: 'bar', alias: 'bar' },
],
),
).toMatchSnapshot();
});
});
describe('process', () => {
test('can use a custom processing strategy', () => {
class ProcessTaco extends Tacos {
readonly slug: string = '';
static process(input: any, parent: any, key: string | undefined): any {
return {
...input,
slug: `thing-${(input as unknown as ProcessTaco).id}`,
};
}
}
const { entities, result } = normalize(ProcessTaco, {
id: '1',
name: 'foo',
});
const final = plainDenormalize(ProcessTaco, result, entities);
expect(final).not.toEqual(expect.any(Symbol));
if (typeof final === 'symbol') return;
expect(final?.slug).toEqual('thing-1');
expect(final).toMatchSnapshot();
});
test('can use information from the parent in the process strategy', () => {
class Child {
id = '';
readonly content: string = '';
readonly parentId: string = '';
readonly parentKey: string = '';
}
class ChildEntity extends EntityMixin(Child) {
static process(input: any, parent: any, key: string | undefined): any {
return {
...input,
parentId: parent?.id,
parentKey: key,
};
}
}
class Parent {
id = '';
readonly content: string = '';
readonly child: ChildEntity = ChildEntity.fromJS({});
}
const ParentEntity = EntityMixin(Parent, {
schema: { child: ChildEntity },
});
const { entities, result } = normalize(ParentEntity, {
id: '1',
content: 'parent',
child: { id: '4', content: 'child' },
});
const final = plainDenormalize(ParentEntity, result, entities);
expect(final).not.toEqual(expect.any(Symbol));
if (typeof final === 'symbol') return;
expect(final?.child?.parentId).toEqual('1');
expect(final).toMatchSnapshot();
});
describe('schema denormalization', () => {
class AttachmentsEntity extends EntityMixin(
class {
id = '';
},
) {}
expect(AttachmentsEntity.key).toBe('AttachmentsEntity');
class Entries {
id = '';
readonly type: string = '';
data = { attachment: undefined };
}
class EntriesEntity extends EntityMixin(Entries) {
static schema = {
data: { attachment: AttachmentsEntity },
};
static process(input: any, parent: any, key: string | undefined): any {
return {
...values(input)[0],
type: Object.keys(input)[0],
};
}
}
class EntriesEntity2 extends EntityMixin(Entries, {
schema: {
data: { attachment: AttachmentsEntity },
},
process(input, parent, key) {
return {
...values(input)[0],
type: Object.keys(input)[0],
};
},
}) {}
it.each([EntriesEntity, EntriesEntity2])(
'is run before and passed to the schema denormalization %s',
EntriesEntity => {
const { entities, result } = normalize(EntriesEntity, {
message: { id: '123', data: { attachment: { id: '456' } } },
});
const final = plainDenormalize(EntriesEntity, result, entities);
expect(final).not.toEqual(expect.any(Symbol));
if (typeof final === 'symbol') return;
expect(final?.type).toEqual('message');
expect(final).toMatchSnapshot();
},
);
});
});
});
describe(`${schema.Entity.name} denormalization`, () => {
test('denormalizes an entity', () => {
const entities = {
Tacos: {
'1': { id: '1', name: 'foo' },
},
};
expect(plainDenormalize(Tacos, '1', entities)).toMatchSnapshot();
expect(
immDenormalize(Tacos, '1', fromJSEntities(entities)),
).toMatchSnapshot();
});
class Food extends EntityMixin(
class {
id = '';
},
) {}
class MenuData {
id = '';
readonly food: Food = Food.fromJS();
}
class Menu extends EntityMixin(MenuData, { schema: { food: Food } }) {}
test('denormalizes deep entities', () => {
const entities = {
Menu: {
'1': { id: '1', food: '1' },
'2': { id: '2' },
},
Food: {
'1': { id: '1' },
},
};
const de1 = plainDenormalize(Menu, '1', entities);
expect(de1).toMatchSnapshot();
expect(immDenormalize(Menu, '1', fromJSEntities(entities))).toEqual(de1);
const de2 = plainDenormalize(Menu, '2', entities);
expect(de2).toMatchSnapshot();
expect(immDenormalize(Menu, '2', fromJSEntities(entities))).toEqual(de2);
});
test('denormalizes deep entities while maintaining referential equality', () => {
const entities = {
Menu: {
'1': { id: '1', food: '1' },
'2': { id: '2' },
},
Food: {
'1': { id: '1' },
},
};
const memo = new SimpleMemoCache();
const first = memo.denormalize(Menu, '1', entities);
const second = memo.denormalize(Menu, '1', entities);
expect(first).not.toEqual(expect.any(Symbol));
if (typeof first === 'symbol') return;
expect(second).not.toEqual(expect.any(Symbol));
if (typeof second === 'symbol') return;
expect(first).toBe(second);
expect(first?.food).toBe(second?.food);
});
test('denormalizes to undefined when validate() returns string', () => {
class MyTacos extends Tacos {
static validate(entity: any) {
if (!Object.hasOwn(entity, 'name')) return 'no name';
}
}
const entities = {
MyTacos: {
'1': { id: '1' },
},
};
expect(plainDenormalize(MyTacos, '1', entities)).toEqual(
expect.any(Symbol),
);
expect(immDenormalize(MyTacos, '1', fromJSEntities(entities))).toEqual(
expect.any(Symbol),
);
});
test('denormalizes to undefined for missing data', () => {
const entities = {
Menu: {
'1': { id: '1', food: '2' },
},
Food: {
'1': { id: '1' },
},
};
expect(plainDenormalize(Menu, '1', entities)).toMatchSnapshot();
expect(
immDenormalize(Menu, '1', fromJSEntities(entities)),
).toMatchSnapshot();
expect(plainDenormalize(Menu, '2', entities)).toMatchSnapshot();
expect(
immDenormalize(Menu, '2', fromJSEntities(entities)),
).toMatchSnapshot();
});
it('should handle optional schema entries Entity', () => {
class MyData {
readonly name: string = '';
readonly secondthing: string = '';
readonly blarb: Date | undefined = undefined;
}
class MyEntity extends EntityMixin(MyData, {
pk: 'name',
schema: { blarb: Temporal.Instant.from },
}) {}
expect(
plainDenormalize(MyEntity, 'bob', {
MyEntity: { bob: { name: 'bob', secondthing: 'hi' } },
}),
).toMatchInlineSnapshot(`
MyEntity {
"blarb": undefined,
"name": "bob",
"secondthing": "hi",
}
`);
});
it('should handle null schema entries Entity', () => {
class MyData {
readonly name: string = '';
readonly secondthing: string = '';
readonly blarb: Date | null = null;
}
class MyEntity extends EntityMixin(MyData, {
pk: 'name',
schema: { blarb: Temporal.Instant.from },
}) {}
expect(
plainDenormalize(MyEntity, 'bob', {
MyEntity: { bob: { name: 'bob', secondthing: 'hi', blarb: null } },
}),
).toMatchInlineSnapshot(`
MyEntity {
"blarb": null,
"name": "bob",
"secondthing": "hi",
}
`);
});
test('denormalizes to undefined for deleted data', () => {
const entities = {
Menu: {
'1': { id: '1', food: '2' },
'2': INVALID,
},
Food: {
'1': { id: '1' },
'2': INVALID,
},
};
expect(plainDenormalize(Menu, '1', entities)).toMatchSnapshot();
expect(
immDenormalize(Menu, '1', fromJSEntities(entities)),
).toMatchSnapshot();
expect(plainDenormalize(Menu, '2', entities)).toMatchSnapshot();
expect(
immDenormalize(Menu, '2', fromJSEntities(entities)),
).toMatchSnapshot();
});
test('can denormalize already partially denormalized data', () => {
const entities = {
Menu: {
'1': { id: '1', food: { id: '1' } },
},
Food: {
// TODO: BREAKING CHANGE: Update this to use main entity and only return nested as 'fallback' in case main entity is not set
'1': { id: '1', extra: 'hi' },
},
};
expect(plainDenormalize(Menu, '1', entities)).toMatchSnapshot();
expect(
immDenormalize(Menu, '1', fromJSEntities(entities)),
).toMatchSnapshot();
});
describe('nesting', () => {
class UserData {
id = '';
readonly role = '';
readonly reports: Report[] = [];
}
class User extends EntityMixin(UserData) {}
class ReportData {
id = '';
readonly title: string = '';
readonly draftedBy: User = User.fromJS();
readonly publishedBy: User = User.fromJS();
}
class Report extends EntityMixin(ReportData, {
schema: {
draftedBy: User,
publishedBy: User,
},
}) {}
User.schema = {
reports: new schema.Array(Report),
};
class CommentData {
id = '';
readonly body: string = '';
readonly author: User = User.fromJS();
}
class Comment extends EntityMixin(CommentData, {
schema: { author: User },
}) {}
test('denormalizes recursive dependencies', () => {
const entities = {
Report: {
'123': {
id: '123',
title: 'Weekly report',
draftedBy: '456',
publishedBy: '456',
},
},