|
| 1 | +import { PolymorphicSerializer, Serializer } from '../lib'; |
| 2 | +import Resource from '../lib/models/resource.model'; |
| 3 | + |
| 4 | +describe('Issue #80 - Polymorphic serializer', () => { |
| 5 | + abstract class Model { |
| 6 | + public type: string; |
| 7 | + |
| 8 | + constructor(public id: string) {} |
| 9 | + } |
| 10 | + |
| 11 | + class Model1 extends Model { |
| 12 | + constructor(id: string, public model1: string) { |
| 13 | + super(id); |
| 14 | + this.type = 'type:Model1'; |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + class Model2 extends Model { |
| 19 | + constructor(id: string, public model2: string) { |
| 20 | + super(id); |
| 21 | + this.type = 'type:Model2'; |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + class Model3 extends Model { |
| 26 | + constructor(id: string, public model2: string) { |
| 27 | + super(id); |
| 28 | + this.type = 'type:Model3'; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + it('should work polymorphicly', async () => { |
| 33 | + const model1: Model1 = new Model1('1', 'model1'); |
| 34 | + const model2: Model2 = new Model2('2', 'model2'); |
| 35 | + const model3: Model3 = new Model3('3', 'model3'); |
| 36 | + |
| 37 | + const Model1Serializer = new Serializer<Model1>('Model1'); |
| 38 | + const Model2Serializer = new Serializer<Model2>('Model2'); |
| 39 | + |
| 40 | + const PolySerializer = new PolymorphicSerializer<Model>('Model', 'type', { |
| 41 | + 'type:Model1': Model1Serializer, |
| 42 | + 'type:Model2': Model2Serializer, |
| 43 | + }); |
| 44 | + |
| 45 | + const data = (await PolySerializer.serialize([model1, model2, model3])) as { |
| 46 | + data: Resource<Model>; |
| 47 | + }; |
| 48 | + |
| 49 | + expect(data.data).toBeInstanceOf(Array); |
| 50 | + expect(data.data).toHaveLength(3); |
| 51 | + expect(data.data[0].id).toEqual('1'); |
| 52 | + expect(data.data[0].type).toEqual('Model1'); |
| 53 | + expect(data.data[1].id).toEqual('2'); |
| 54 | + expect(data.data[1].type).toEqual('Model2'); |
| 55 | + expect(data.data[2].id).toEqual('3'); |
| 56 | + expect(data.data[2].type).toEqual('Model'); |
| 57 | + }); |
| 58 | +}); |
0 commit comments