/
MagicObject.test.ts
89 lines (64 loc) · 2.1 KB
/
MagicObject.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
import { stringToCamelCase } from '@/helpers/string_helpers';
import MagicObject from './MagicObject';
type Attributes = Record<string, unknown>;
class Stub extends MagicObject {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[property: string]: any;
public constructor(attributes: Attributes) {
super();
this.initializeAttributes(attributes);
}
public getAttributes(): Attributes {
return this.attributes;
}
protected initializeAttributes(attributes: Attributes): void {
if (this.static().isConjuring()) {
this.reserveProperty('attributes');
return;
}
this.attributes = Object.entries(attributes).reduce((attributes, [name, value]) => {
attributes[stringToCamelCase(name)] = value;
return attributes;
}, {} as Attributes);
}
protected __get(property: string): unknown {
return this.attributes[property];
}
protected __set(property: string, value: unknown): void {
this.attributes[property] = value;
}
protected __delete(property: string): void {
delete this.attributes[property];
}
}
describe('MagicObject', () => {
it('Intercepts getters and setters', () => {
// Arrange
const object = new Stub({ lorem: 'ipsum' });
// Act
object.foo = 'bar';
// Assert
expect(object.foo).toEqual('bar');
expect(object.lorem).toEqual('ipsum');
expect(object.getAttributes()).toEqual({
lorem: 'ipsum',
foo: 'bar',
});
});
it('Intercepts delete', () => {
// Arrange
const object = new Stub({ lorem: 'ipsum' });
// Act
delete object.lorem;
// Assert
expect(object.lorem).toBeUndefined();
expect(object.getAttributes()).toEqual({});
});
it('Runs methods in constructor', () => {
// Act
const object = new Stub({ 'foo-bar': true });
// Assert
expect(object['foo-bar']).toBeUndefined();
expect(object.fooBar).toBe(true);
});
});