Skip to content

Commit a68c61d

Browse files
committed
Fixed bug #80 that instance function worked different if Proxy was supported or not
With Proxy support instance function always returned new object, without support it was always same instance. This changed fixes this issue and instance function now always returns same object.
1 parent e48a85d commit a68c61d

File tree

4 files changed

+26
-7
lines changed

4 files changed

+26
-7
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "ts-mockito",
3-
"version": "2.2.7",
3+
"version": "2.2.8",
44
"description": "Mocking library for TypeScript",
55
"main": "lib/ts-mockito.js",
66
"typings": "lib/ts-mockito",

src/Mock.ts

+4
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ export class Mocker {
1919
private objectPropertyCodeRetriever = new ObjectPropertyCodeRetriever();
2020

2121
constructor(private clazz: any, protected instance: any = {}) {
22+
if (typeof Proxy !== "undefined") {
23+
this.instance = new Proxy(this.instance, this.createCatchAllHandlerForRemainingPropertiesWithoutGetters());
24+
}
25+
2226
this.mock.__tsmockitoInstance = this.instance;
2327
this.mock.__tsmockitoMocker = this;
2428
if (_.isObject(this.clazz) && _.isObject(this.instance)) {

src/ts-mockito.ts

+1-6
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,7 @@ export function when<T>(method: T): MethodStubSetter<T> {
4545

4646
export function instance<T>(mockedValue: T): T {
4747
const tsmockitoInstance = (mockedValue as any).__tsmockitoInstance as T;
48-
if (typeof Proxy === "undefined") {
49-
return tsmockitoInstance;
50-
}
51-
52-
const tsmockitoMocker = (mockedValue as any).__tsmockitoMocker as Mocker;
53-
return new Proxy(tsmockitoInstance as any, tsmockitoMocker.createCatchAllHandlerForRemainingPropertiesWithoutGetters());
48+
return tsmockitoInstance;
5449
}
5550

5651
export function capture<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(method: (a: T0, b: T1, c: T2, d: T3, e: T4, f: T5, g: T6, h: T7, i: T8, j: T9) => any): ArgCaptor10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>;

test/instance.spec.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import {instance, mock} from "../src/ts-mockito";
2+
import {Foo} from "./utils/Foo";
3+
4+
describe("instance", () => {
5+
describe("getting instance of mock", () => {
6+
let mockedFoo: Foo;
7+
8+
it("returns always same instance", () => {
9+
// given
10+
mockedFoo = mock(Foo);
11+
12+
// when
13+
let firstFooInstance = instance(mockedFoo);
14+
let secondFooInstance = instance(mockedFoo);
15+
16+
// then
17+
expect(firstFooInstance).toBe(secondFooInstance);
18+
});
19+
});
20+
});

0 commit comments

Comments
 (0)