From 4152838465240c6ac888f9e0336d2438e0a986c4 Mon Sep 17 00:00:00 2001 From: Jesse Carter Date: Sun, 13 Dec 2020 11:30:24 -0500 Subject: [PATCH] fix(ts-jest): handling falsy values and undefined check for presence of property instead of relying on whether or not it is truthy fix #211 --- packages/testing/src/mocks.spec.ts | 30 ++++++++++++++++++++++++++++++ packages/testing/src/mocks.ts | 26 ++++++++++++++------------ 2 files changed, 44 insertions(+), 12 deletions(-) diff --git a/packages/testing/src/mocks.spec.ts b/packages/testing/src/mocks.spec.ts index 68c8464d8..d8dcd41b1 100644 --- a/packages/testing/src/mocks.spec.ts +++ b/packages/testing/src/mocks.spec.ts @@ -5,6 +5,8 @@ import { createMock, DeepMocked } from './mocks'; interface TestInterface { someNum: number; + someBool: boolean; + optional: string | undefined; func: (num: number, str: string) => boolean; } @@ -42,6 +44,34 @@ describe('Mocks', () => { expect(mock.switchToHttp).toBeCalledTimes(1); }); + it('should work with truthy values properties', () => { + const mock = createMock({ + someNum: 1, + someBool: true, + }); + + expect(mock.someNum).toBe(1); + expect(mock.someBool).toBe(true); + }); + + it('should work with falsy values properties', () => { + const mock = createMock({ + someNum: 0, + someBool: false, + }); + + expect(mock.someNum).toBe(0); + expect(mock.someBool).toBe(false); + }); + + it('should work with optional values explicitly returning undefined', () => { + const mock = createMock({ + optional: undefined, + }); + + expect(mock.optional).toBe(undefined); + }); + it('should work with properties and functions', () => { const mock = createMock({ someNum: 42, diff --git a/packages/testing/src/mocks.ts b/packages/testing/src/mocks.ts index 7354a8472..5d578cfc3 100644 --- a/packages/testing/src/mocks.ts +++ b/packages/testing/src/mocks.ts @@ -34,13 +34,14 @@ const createRecursiveMockProxy = (name: string) => { const checkProp = obj[prop]; - const mockedProp = checkProp - ? typeof checkProp === 'function' - ? jest.fn() - : checkProp - : propName === 'then' - ? undefined - : createRecursiveMockProxy(propName); + const mockedProp = + prop in obj + ? typeof checkProp === 'function' + ? jest.fn() + : checkProp + : propName === 'then' + ? undefined + : createRecursiveMockProxy(propName); cache.set(prop, mockedProp); @@ -81,11 +82,12 @@ export const createMock = ( const checkProp = obj[prop]; - const mockedProp = checkProp - ? typeof checkProp === 'function' - ? jest.fn(checkProp) - : checkProp - : createRecursiveMockProxy(`${name}.${prop.toString()}`); + const mockedProp = + prop in obj + ? typeof checkProp === 'function' + ? jest.fn(checkProp) + : checkProp + : createRecursiveMockProxy(`${name}.${prop.toString()}`); cache.set(prop, mockedProp); return mockedProp;