-
Notifications
You must be signed in to change notification settings - Fork 510
/
Copy pathpromise-field.spec.ts
83 lines (66 loc) · 2.14 KB
/
promise-field.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
import 'reflect-metadata';
import { defaultMetadataStorage } from '../../src/storage';
import { plainToInstance, Type, instanceToPlain } from '../../src';
describe('promise field', () => {
it('should transform plan to class with promise field', async () => {
defaultMetadataStorage.clear();
class PromiseClass {
promise: Promise<string>;
}
const plain = {
promise: Promise.resolve('hi'),
};
const instance = plainToInstance(PromiseClass, plain);
expect(instance.promise).toBeInstanceOf(Promise);
const value = await instance.promise;
expect(value).toBe('hi');
});
it('should transform class with promise field to plain', async () => {
class PromiseClass {
promise: Promise<string>;
constructor(promise: Promise<any>) {
this.promise = promise;
}
}
const instance = new PromiseClass(Promise.resolve('hi'));
const plain = instanceToPlain(instance) as any;
expect(plain).toHaveProperty('promise');
const value = await plain.promise;
expect(value).toBe('hi');
});
it('should clone promise result', async () => {
defaultMetadataStorage.clear();
class PromiseClass {
promise: Promise<string[]>;
}
const array = ['hi', 'my', 'name'];
const plain = {
promise: Promise.resolve(array),
};
const instance = plainToInstance(PromiseClass, plain);
const value = await instance.promise;
expect(value).toEqual(array);
// modify transformed array to prove it's not referencing original array
value.push('is');
expect(value).not.toEqual(array);
});
it('should support Type decorator', async () => {
class PromiseClass {
@Type(() => InnerClass)
promise: Promise<InnerClass>;
}
class InnerClass {
position: string;
constructor(position: string) {
this.position = position;
}
}
const plain = {
promise: Promise.resolve(new InnerClass('developer')),
};
const instance = plainToInstance(PromiseClass, plain);
const value = await instance.promise;
expect(value).toBeInstanceOf(InnerClass);
expect(value.position).toBe('developer');
});
});