|
| 1 | +// This is a modification of the code found in https://github.com/marchaos/jest-mock-extended |
| 2 | +// to better support deep mocking of objects. |
| 3 | + |
| 4 | +// MIT License |
| 5 | + |
| 6 | +// Copyright (c) 2019 Marc McIntyre |
| 7 | + |
| 8 | +// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 9 | +// of this software and associated documentation files (the "Software"), to deal |
| 10 | +// in the Software without restriction, including without limitation the rights |
| 11 | +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 12 | +// copies of the Software, and to permit persons to whom the Software is |
| 13 | +// furnished to do so, subject to the following conditions: |
| 14 | + |
| 15 | +// The above copyright notice and this permission notice shall be included in all |
| 16 | +// copies or substantial portions of the Software. |
| 17 | + |
| 18 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 19 | +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 20 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 21 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 22 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 23 | +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 24 | +// SOFTWARE. |
| 25 | + |
| 26 | +import { jest } from "@jest/globals"; |
| 27 | +import { FunctionLike } from "jest-mock"; |
| 28 | +import { calledWithFn, MatchersOrLiterals } from "jest-mock-extended"; |
| 29 | +import { PartialDeep } from "type-fest"; |
| 30 | + |
| 31 | +type ProxiedProperty = string | number | symbol; |
| 32 | + |
| 33 | +export interface GlobalConfig { |
| 34 | + // ignoreProps is required when we don't want to return anything for a mock (for example, when mocking a promise). |
| 35 | + ignoreProps?: ProxiedProperty[]; |
| 36 | +} |
| 37 | + |
| 38 | +const DEFAULT_CONFIG: GlobalConfig = { |
| 39 | + ignoreProps: ["then"], |
| 40 | +}; |
| 41 | + |
| 42 | +let GLOBAL_CONFIG = DEFAULT_CONFIG; |
| 43 | + |
| 44 | +export const JestMockExtended = { |
| 45 | + DEFAULT_CONFIG, |
| 46 | + configure: (config: GlobalConfig) => { |
| 47 | + // Shallow merge so they can override anything they want. |
| 48 | + GLOBAL_CONFIG = { ...DEFAULT_CONFIG, ...config }; |
| 49 | + }, |
| 50 | + resetConfig: () => { |
| 51 | + GLOBAL_CONFIG = DEFAULT_CONFIG; |
| 52 | + }, |
| 53 | +}; |
| 54 | + |
| 55 | +export interface CalledWithMock<T extends FunctionLike> extends jest.Mock<T> { |
| 56 | + calledWith: (...args: [...MatchersOrLiterals<Parameters<T>>]) => jest.Mock<T>; |
| 57 | +} |
| 58 | + |
| 59 | +export interface MockDeepMock<R> { |
| 60 | + mockDeep: () => DeepMockProxy<R>; |
| 61 | +} |
| 62 | + |
| 63 | +export interface ReplaceProperty<T> { |
| 64 | + /** |
| 65 | + * mockDeep will by default return a jest.fn() for all properties, |
| 66 | + * but this allows you to replace the property with a value. |
| 67 | + * @param value The value to replace the property with. |
| 68 | + */ |
| 69 | + replaceProperty(value: T): void; |
| 70 | +} |
| 71 | + |
| 72 | +export type _MockProxy<T> = { |
| 73 | + [K in keyof T]: T[K] extends FunctionLike ? T[K] & CalledWithMock<T[K]> : T[K]; |
| 74 | +}; |
| 75 | + |
| 76 | +export type MockProxy<T> = _MockProxy<T> & T; |
| 77 | + |
| 78 | +export type _DeepMockProxy<T> = { |
| 79 | + // This supports deep mocks in the else branch |
| 80 | + [K in keyof T]: T[K] extends (...args: infer A) => infer R |
| 81 | + ? T[K] & CalledWithMock<T[K]> & MockDeepMock<R> |
| 82 | + : T[K] & ReplaceProperty<T[K]> & _DeepMockProxy<T[K]>; |
| 83 | +}; |
| 84 | + |
| 85 | +// we intersect with T here instead of on the mapped type above to |
| 86 | +// prevent immediate type resolution on a recursive type, this will |
| 87 | +// help to improve performance for deeply nested recursive mocking |
| 88 | +// at the same time, this intersection preserves private properties |
| 89 | +export type DeepMockProxy<T> = _DeepMockProxy<T> & T; |
| 90 | + |
| 91 | +export type _DeepMockProxyWithFuncPropSupport<T> = { |
| 92 | + // This supports deep mocks in the else branch |
| 93 | + [K in keyof T]: T[K] extends FunctionLike |
| 94 | + ? CalledWithMock<T[K]> & DeepMockProxy<T[K]> |
| 95 | + : DeepMockProxy<T[K]>; |
| 96 | +}; |
| 97 | + |
| 98 | +export type DeepMockProxyWithFuncPropSupport<T> = _DeepMockProxyWithFuncPropSupport<T> & T; |
| 99 | + |
| 100 | +export interface MockOpts { |
| 101 | + deep?: boolean; |
| 102 | + fallbackMockImplementation?: (...args: any[]) => any; |
| 103 | +} |
| 104 | + |
| 105 | +export const mockClear = (mock: MockProxy<any>) => { |
| 106 | + for (const key of Object.keys(mock)) { |
| 107 | + if (mock[key] === null || mock[key] === undefined) { |
| 108 | + continue; |
| 109 | + } |
| 110 | + |
| 111 | + if (mock[key]._isMockObject) { |
| 112 | + mockClear(mock[key]); |
| 113 | + } |
| 114 | + |
| 115 | + if (mock[key]._isMockFunction) { |
| 116 | + mock[key].mockClear(); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + // This is a catch for if they pass in a jest.fn() |
| 121 | + if (!mock._isMockObject) { |
| 122 | + return mock.mockClear(); |
| 123 | + } |
| 124 | +}; |
| 125 | + |
| 126 | +export const mockReset = (mock: MockProxy<any>) => { |
| 127 | + for (const key of Object.keys(mock)) { |
| 128 | + if (mock[key] === null || mock[key] === undefined) { |
| 129 | + continue; |
| 130 | + } |
| 131 | + |
| 132 | + if (mock[key]._isMockObject) { |
| 133 | + mockReset(mock[key]); |
| 134 | + } |
| 135 | + if (mock[key]._isMockFunction) { |
| 136 | + mock[key].mockReset(); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + // This is a catch for if they pass in a jest.fn() |
| 141 | + // Worst case, we will create a jest.fn() (since this is a proxy) |
| 142 | + // below in the get and call mockReset on it |
| 143 | + if (!mock._isMockObject) { |
| 144 | + return mock.mockReset(); |
| 145 | + } |
| 146 | +}; |
| 147 | + |
| 148 | +export function mockDeep<T>( |
| 149 | + opts: { |
| 150 | + funcPropSupport?: true; |
| 151 | + fallbackMockImplementation?: MockOpts["fallbackMockImplementation"]; |
| 152 | + }, |
| 153 | + mockImplementation?: PartialDeep<T>, |
| 154 | +): DeepMockProxyWithFuncPropSupport<T>; |
| 155 | +export function mockDeep<T>(mockImplementation?: PartialDeep<T>): DeepMockProxy<T>; |
| 156 | +export function mockDeep(arg1: any, arg2?: any) { |
| 157 | + const [opts, mockImplementation] = |
| 158 | + typeof arg1 === "object" && |
| 159 | + (typeof arg1.fallbackMockImplementation === "function" || arg1.funcPropSupport === true) |
| 160 | + ? [arg1, arg2] |
| 161 | + : [{}, arg1]; |
| 162 | + return mock(mockImplementation, { |
| 163 | + deep: true, |
| 164 | + fallbackMockImplementation: opts.fallbackMockImplementation, |
| 165 | + }); |
| 166 | +} |
| 167 | + |
| 168 | +const overrideMockImp = (obj: PartialDeep<any>, opts?: MockOpts) => { |
| 169 | + const proxy = new Proxy<MockProxy<any>>(obj, handler(opts)); |
| 170 | + for (const name of Object.keys(obj)) { |
| 171 | + if (typeof obj[name] === "object" && obj[name] !== null) { |
| 172 | + proxy[name] = overrideMockImp(obj[name], opts); |
| 173 | + } else { |
| 174 | + proxy[name] = obj[name]; |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + return proxy; |
| 179 | +}; |
| 180 | + |
| 181 | +const handler = (opts?: MockOpts): ProxyHandler<any> => ({ |
| 182 | + ownKeys(target: MockProxy<any>) { |
| 183 | + return Reflect.ownKeys(target); |
| 184 | + }, |
| 185 | + |
| 186 | + set: (obj: MockProxy<any>, property: ProxiedProperty, value: any) => { |
| 187 | + obj[property] = value; |
| 188 | + return true; |
| 189 | + }, |
| 190 | + |
| 191 | + get: (obj: MockProxy<any>, property: ProxiedProperty) => { |
| 192 | + const fn = calledWithFn({ fallbackMockImplementation: opts?.fallbackMockImplementation }); |
| 193 | + |
| 194 | + if (!(property in obj)) { |
| 195 | + if (GLOBAL_CONFIG.ignoreProps?.includes(property)) { |
| 196 | + return undefined; |
| 197 | + } |
| 198 | + // Jest's internal equality checking does some wierd stuff to check for iterable equality |
| 199 | + if (property === Symbol.iterator) { |
| 200 | + return obj[property]; |
| 201 | + } |
| 202 | + |
| 203 | + if (property === "_deepMock") { |
| 204 | + return obj[property]; |
| 205 | + } |
| 206 | + // So this calls check here is totally not ideal - jest internally does a |
| 207 | + // check to see if this is a spy - which we want to say no to, but blindly returning |
| 208 | + // an proxy for calls results in the spy check returning true. This is another reason |
| 209 | + // why deep is opt in. |
| 210 | + if (opts?.deep && property !== "calls") { |
| 211 | + obj[property] = new Proxy<MockProxy<any>>(fn, handler(opts)); |
| 212 | + obj[property].replaceProperty = <T extends typeof obj, K extends keyof T>(value: T[K]) => { |
| 213 | + obj[property] = value; |
| 214 | + }; |
| 215 | + obj[property].mockDeep = () => { |
| 216 | + if (obj[property]._deepMock) { |
| 217 | + return obj[property]._deepMock; |
| 218 | + } |
| 219 | + |
| 220 | + const mock = mockDeep({ |
| 221 | + fallbackMockImplementation: opts?.fallbackMockImplementation, |
| 222 | + }); |
| 223 | + (obj[property] as CalledWithMock<any>).mockReturnValue(mock); |
| 224 | + obj[property]._deepMock = mock; |
| 225 | + return mock; |
| 226 | + }; |
| 227 | + obj[property]._isMockObject = true; |
| 228 | + } else { |
| 229 | + obj[property] = calledWithFn({ |
| 230 | + fallbackMockImplementation: opts?.fallbackMockImplementation, |
| 231 | + }); |
| 232 | + } |
| 233 | + } |
| 234 | + |
| 235 | + // @ts-expect-error Hack by author of jest-mock-extended |
| 236 | + if (obj instanceof Date && typeof obj[property] === "function") { |
| 237 | + // @ts-expect-error Hack by author of jest-mock-extended |
| 238 | + return obj[property].bind(obj); |
| 239 | + } |
| 240 | + |
| 241 | + return obj[property]; |
| 242 | + }, |
| 243 | +}); |
| 244 | + |
| 245 | +const mock = <T, MockedReturn extends MockProxy<T> & T = MockProxy<T> & T>( |
| 246 | + mockImplementation: PartialDeep<T> = {} as PartialDeep<T>, |
| 247 | + opts?: MockOpts, |
| 248 | +): MockedReturn => { |
| 249 | + // @ts-expect-error private |
| 250 | + mockImplementation!._isMockObject = true; |
| 251 | + return overrideMockImp(mockImplementation, opts); |
| 252 | +}; |
| 253 | + |
| 254 | +export const mockFn = <T extends FunctionLike>(): CalledWithMock<T> & T => { |
| 255 | + // @ts-expect-error Hack by author of jest-mock-extended |
| 256 | + return calledWithFn(); |
| 257 | +}; |
| 258 | + |
| 259 | +export const stub = <T extends object>(): T => { |
| 260 | + return new Proxy<T>({} as T, { |
| 261 | + get: (obj, property: ProxiedProperty) => { |
| 262 | + if (property in obj) { |
| 263 | + // @ts-expect-error Hack by author of jest-mock-extended |
| 264 | + return obj[property]; |
| 265 | + } |
| 266 | + return jest.fn(); |
| 267 | + }, |
| 268 | + }); |
| 269 | +}; |
| 270 | + |
| 271 | +export default mock; |
0 commit comments