UNPKG

2.27 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const spy_call_1 = require("./spy-call");
4class PropertySpy {
5 constructor(target, propertyName) {
6 this._getCalls = [];
7 this._setCalls = [];
8 this._descriptorTarget = target;
9 this._propertyName = propertyName;
10 if (!Object.getOwnPropertyDescriptor(target, this._propertyName)) {
11 this._descriptorTarget = target.constructor.prototype;
12 }
13 const propertyDescriptor = Object.getOwnPropertyDescriptor(this._descriptorTarget, this._propertyName);
14 if (propertyDescriptor === undefined) {
15 throw new TypeError(`${propertyName} is not a property.`);
16 }
17 this._originialGetter = propertyDescriptor.get;
18 this._originialSetter = propertyDescriptor.set;
19 this._getter = this._originialGetter;
20 this._setter = this._originialSetter;
21 this._descriptorTarget = target;
22 Object.defineProperty(this._descriptorTarget, this._propertyName, {
23 get: this._get.bind(this),
24 set: this._set.bind(this)
25 });
26 }
27 get setCalls() {
28 return this._setCalls;
29 }
30 andReturnValue(value) {
31 this._value = value;
32 this._returnValue = true;
33 return this;
34 }
35 andCallGetter(getter) {
36 this._getter = getter;
37 this._returnValue = false;
38 return this;
39 }
40 andCallSetter(setter) {
41 this._setter = setter;
42 this._returnValue = false;
43 return this;
44 }
45 restore() {
46 Object.defineProperty(this._descriptorTarget, this._propertyName, {
47 get: this._originialGetter,
48 set: this._originialSetter
49 });
50 }
51 _get() {
52 this._getCalls.push(new spy_call_1.SpyCall([]));
53 if (this._returnValue) {
54 return this._value;
55 }
56 return this._getter ? this._getter.call(this._descriptorTarget) : undefined;
57 }
58 _set(value) {
59 this._setCalls.push(new spy_call_1.SpyCall([value]));
60 this._setter.call(this._descriptorTarget, value);
61 if (!this._returnValue) {
62 this._value = value;
63 }
64 }
65}
66exports.PropertySpy = PropertySpy;
67//# sourceMappingURL=property-spy.js.map
\No newline at end of file