|
| 1 | +import type { AnyCallable, MockInstance } from './types.ts' |
| 2 | + |
| 3 | +/** Get the fallback implementation of a mock if no matching stub is found. */ |
| 4 | +export const getFallbackImplementation = <TFunc extends AnyCallable>( |
| 5 | + mock: MockInstance<TFunc>, |
| 6 | +): TFunc | undefined => { |
| 7 | + return ( |
| 8 | + mock.getMockImplementation() ?? getTinyspyInternals(mock)?.getOriginal() |
| 9 | + ) |
| 10 | +} |
| 11 | + |
| 12 | +/** Internal state from Tinyspy, where a mock's default implementation is stored. */ |
| 13 | +interface TinyspyInternals<TFunc extends AnyCallable> { |
| 14 | + getOriginal: () => TFunc | undefined |
| 15 | +} |
| 16 | + |
| 17 | +/** |
| 18 | + * Get the fallback implementation out of tinyspy internals. |
| 19 | + * |
| 20 | + * This slight hack works around a bug in Vitest <= 3 |
| 21 | + * where `getMockImplementation` will return `undefined` after `mockReset`, |
| 22 | + * even if a default implementation is still active. |
| 23 | + * The implementation remains present in tinyspy internal state, |
| 24 | + * which is stored on a Symbol key in the mock object. |
| 25 | + */ |
| 26 | +const getTinyspyInternals = <TFunc extends AnyCallable>( |
| 27 | + mock: MockInstance<TFunc>, |
| 28 | +): TinyspyInternals<TFunc> | undefined => { |
| 29 | + const maybeTinyspy = mock as unknown as Record<PropertyKey, unknown> |
| 30 | + |
| 31 | + for (const key of Object.getOwnPropertySymbols(maybeTinyspy)) { |
| 32 | + const maybeTinyspyInternals = maybeTinyspy[key] |
| 33 | + |
| 34 | + if ( |
| 35 | + maybeTinyspyInternals && |
| 36 | + typeof maybeTinyspyInternals === 'object' && |
| 37 | + 'getOriginal' in maybeTinyspyInternals && |
| 38 | + typeof maybeTinyspyInternals.getOriginal === 'function' |
| 39 | + ) { |
| 40 | + return maybeTinyspyInternals as TinyspyInternals<TFunc> |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return undefined |
| 45 | +} |
0 commit comments