From a68c61d0b79bc9be9af2bafaf7ca1a7c7eb184eb Mon Sep 17 00:00:00 2001 From: NagRock Date: Tue, 23 Jan 2018 17:01:11 +0100 Subject: [PATCH] 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. --- package.json | 2 +- src/Mock.ts | 4 ++++ src/ts-mockito.ts | 7 +------ test/instance.spec.ts | 20 ++++++++++++++++++++ 4 files changed, 26 insertions(+), 7 deletions(-) create mode 100644 test/instance.spec.ts diff --git a/package.json b/package.json index 0d6ec45..0c9811d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ts-mockito", - "version": "2.2.7", + "version": "2.2.8", "description": "Mocking library for TypeScript", "main": "lib/ts-mockito.js", "typings": "lib/ts-mockito", diff --git a/src/Mock.ts b/src/Mock.ts index 79d3f88..e42e472 100644 --- a/src/Mock.ts +++ b/src/Mock.ts @@ -19,6 +19,10 @@ export class Mocker { private objectPropertyCodeRetriever = new ObjectPropertyCodeRetriever(); constructor(private clazz: any, protected instance: any = {}) { + if (typeof Proxy !== "undefined") { + this.instance = new Proxy(this.instance, this.createCatchAllHandlerForRemainingPropertiesWithoutGetters()); + } + this.mock.__tsmockitoInstance = this.instance; this.mock.__tsmockitoMocker = this; if (_.isObject(this.clazz) && _.isObject(this.instance)) { diff --git a/src/ts-mockito.ts b/src/ts-mockito.ts index 12cd3e1..38f65e6 100644 --- a/src/ts-mockito.ts +++ b/src/ts-mockito.ts @@ -45,12 +45,7 @@ export function when(method: T): MethodStubSetter { export function instance(mockedValue: T): T { const tsmockitoInstance = (mockedValue as any).__tsmockitoInstance as T; - if (typeof Proxy === "undefined") { - return tsmockitoInstance; - } - - const tsmockitoMocker = (mockedValue as any).__tsmockitoMocker as Mocker; - return new Proxy(tsmockitoInstance as any, tsmockitoMocker.createCatchAllHandlerForRemainingPropertiesWithoutGetters()); + return tsmockitoInstance; } export function capture(method: (a: T0, b: T1, c: T2, d: T3, e: T4, f: T5, g: T6, h: T7, i: T8, j: T9) => any): ArgCaptor10; diff --git a/test/instance.spec.ts b/test/instance.spec.ts new file mode 100644 index 0000000..e0ba2d0 --- /dev/null +++ b/test/instance.spec.ts @@ -0,0 +1,20 @@ +import {instance, mock} from "../src/ts-mockito"; +import {Foo} from "./utils/Foo"; + +describe("instance", () => { + describe("getting instance of mock", () => { + let mockedFoo: Foo; + + it("returns always same instance", () => { + // given + mockedFoo = mock(Foo); + + // when + let firstFooInstance = instance(mockedFoo); + let secondFooInstance = instance(mockedFoo); + + // then + expect(firstFooInstance).toBe(secondFooInstance); + }); + }); +});