Skip to content

Commit

Permalink
Merge pull request #123 from millsp/perf/types/deep-mock
Browse files Browse the repository at this point in the history
perf(types): prevent immediate deep and circular resolution for deep mock
  • Loading branch information
marchaos authored Aug 3, 2023
2 parents 1860950 + 7cb9815 commit 23279af
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions src/Mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,35 @@ export interface CalledWithMock<T, Y extends any[]> extends jest.Mock<T, Y> {
calledWith: (...args: Y | MatchersOrLiterals<Y>) => jest.Mock<T, Y>;
}

export type MockProxy<T> = {
[K in keyof T]: T[K] extends (...args: infer A) => infer B ? CalledWithMock<B, A> : T[K];
} &
T;
export type _MockProxy<T> = {
[K in keyof T]: T[K] extends (...args: infer A) => infer B
? T[K] & CalledWithMock<B, A>
: T[K];
};

export type MockProxy<T> = _MockProxy<T> & T;

export type DeepMockProxy<T> = {
export type _DeepMockProxy<T> = {
// This supports deep mocks in the else branch
[K in keyof T]: T[K] extends (...args: infer A) => infer B ? CalledWithMock<B, A> : DeepMockProxy<T[K]>;
} &
T;
[K in keyof T]: T[K] extends (...args: infer A) => infer B
? T[K] & CalledWithMock<B, A>
: T[K] & _DeepMockProxy<T[K]>;
};

export type DeepMockProxyWithFuncPropSupport<T> = {
// we intersect with T here instead of on the mapped type above to
// prevent immediate type resolution on a recursive type, this will
// help to improve performance for deeply nested recursive mocking
// at the same time, this intersection preserves private properties
export type DeepMockProxy<T> = _DeepMockProxy<T> & T;

export type _DeepMockProxyWithFuncPropSupport<T> = {
// This supports deep mocks in the else branch
[K in keyof T]: T[K] extends (...args: infer A) => infer B ? CalledWithMock<B, A> & DeepMockProxy<T[K]> : DeepMockProxy<T[K]>;
} &
T;
[K in keyof T]: T[K] extends (...args: infer A) => infer B
? CalledWithMock<B, A> & DeepMockProxy<T[K]>
: DeepMockProxy<T[K]>;
};

export type DeepMockProxyWithFuncPropSupport<T> = _DeepMockProxyWithFuncPropSupport<T> & T;

export interface MockOpts {
deep?: boolean;
Expand Down

0 comments on commit 23279af

Please sign in to comment.