Skip to content

Commit

Permalink
fix(ts-jest): ensures auto mocked properties can be casted to primiti…
Browse files Browse the repository at this point in the history
…ve types (golevelup#850)

Addresses a unintended behaviour change introduced in version 0.5.1

fix golevelup#843
  • Loading branch information
JonasFaure authored Oct 8, 2024
1 parent 72fc745 commit 60cc5f8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
20 changes: 20 additions & 0 deletions packages/testing/ts-jest/src/mocks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<TestInterface>();
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<any>();
Expand Down
13 changes: 13 additions & 0 deletions packages/testing/ts-jest/src/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
},
Expand Down

0 comments on commit 60cc5f8

Please sign in to comment.