Skip to content

Commit

Permalink
Merge pull request #212 from golevelup/fix/mocks-falsy-and-undefined-…
Browse files Browse the repository at this point in the history
…values

fix(ts-jest): handling falsy values and undefined
  • Loading branch information
WonderPanda authored Dec 13, 2020
2 parents 00b2fd2 + 4152838 commit 8b64d83
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 12 deletions.
30 changes: 30 additions & 0 deletions packages/testing/src/mocks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { createMock, DeepMocked } from './mocks';

interface TestInterface {
someNum: number;
someBool: boolean;
optional: string | undefined;
func: (num: number, str: string) => boolean;
}

Expand Down Expand Up @@ -42,6 +44,34 @@ describe('Mocks', () => {
expect(mock.switchToHttp).toBeCalledTimes(1);
});

it('should work with truthy values properties', () => {
const mock = createMock<TestInterface>({
someNum: 1,
someBool: true,
});

expect(mock.someNum).toBe(1);
expect(mock.someBool).toBe(true);
});

it('should work with falsy values properties', () => {
const mock = createMock<TestInterface>({
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<TestInterface>({
optional: undefined,
});

expect(mock.optional).toBe(undefined);
});

it('should work with properties and functions', () => {
const mock = createMock<TestInterface>({
someNum: 42,
Expand Down
26 changes: 14 additions & 12 deletions packages/testing/src/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -81,11 +82,12 @@ export const createMock = <T extends object>(

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;
Expand Down

0 comments on commit 8b64d83

Please sign in to comment.