From 60cc5f8f96086ee4621d32a68b7fbaab49733c38 Mon Sep 17 00:00:00 2001 From: Jonas Faure <47354296+JonasFaure@users.noreply.github.com> Date: Tue, 8 Oct 2024 15:50:21 +0200 Subject: [PATCH] fix(ts-jest): ensures auto mocked properties can be casted to primitive types (#850) Addresses a unintended behaviour change introduced in version 0.5.1 fix #843 --- packages/testing/ts-jest/src/mocks.spec.ts | 20 ++++++++++++++++++++ packages/testing/ts-jest/src/mocks.ts | 13 +++++++++++++ 2 files changed, 33 insertions(+) diff --git a/packages/testing/ts-jest/src/mocks.spec.ts b/packages/testing/ts-jest/src/mocks.spec.ts index f66db2073..030f90495 100644 --- a/packages/testing/ts-jest/src/mocks.spec.ts +++ b/packages/testing/ts-jest/src/mocks.spec.ts @@ -9,6 +9,7 @@ interface TestInterface { optional: string | undefined; func: (num: number, str: string) => boolean; func2: (entity: TestClass) => void; + func3: () => Promise<{ prop: number }>; } class TestClass { @@ -225,6 +226,25 @@ describe('Mocks', () => { expect(mock.toString()).toEqual('[object Object]'); expect(mock.nested.toString()).toEqual('function () { [native code] }'); }); + it('nested properties can be implictly casted to string', () => { + const mock = createMock<{ nested: any }>(); + + const testFnNumber = () => mock.nested > 0; + const testFnString = () => `${mock.nested}`; + + expect(testFnNumber).not.toThrowError(); + expect(testFnString).not.toThrowError(); + }); + it('mocked functions returned values can be implictly casted to string', async () => { + const mock = createMock(); + const result = await mock.func3(); + + const testFnNumber = () => result.prop > 0; + const testFnString = () => `${result.prop}`; + + expect(testFnNumber).not.toThrowError(); + expect(testFnString).not.toThrowError(); + }); it('asymmetricMatch should not be set', () => { const mock = createMock(); diff --git a/packages/testing/ts-jest/src/mocks.ts b/packages/testing/ts-jest/src/mocks.ts index 14e147d77..9d66c5327 100644 --- a/packages/testing/ts-jest/src/mocks.ts +++ b/packages/testing/ts-jest/src/mocks.ts @@ -85,6 +85,19 @@ const createProxy: { mockedProp = createProxy(`${name}.${propName}`); } + // Add Symbol.toPrimitive to preserve implicit conversion to primitive types + if (typeof mockedProp === 'object' || typeof mockedProp === 'function') { + mockedProp[Symbol.toPrimitive] = (hint) => { + if (hint === 'string') { + return 'mocked'; + } + if (hint === 'number') { + return 0; + } + throw new TypeError(); + }; + } + cache.set(prop, mockedProp); return mockedProp; },