• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mcous / vitest-when / 17324292113

29 Aug 2025 12:51PM UTC coverage: 99.024% (-1.0%) from 100.0%
17324292113

push

github

web-flow
fix: work around `getMockImplementation()` in Vitest (#28)

Ensure that default implementations set via `vi.fn(default_impl)` are used,
even when Vitest forgets they exists, by pulling from tinyspy internals

70 of 71 branches covered (98.59%)

Branch coverage included in aggregate %.

9 of 10 new or added lines in 2 files covered. (90.0%)

133 of 134 relevant lines covered (99.25%)

186.78 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.24
/src/fallback-implementation.ts
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>(
27✔
5
  mock: MockInstance<TFunc>,
6
): TFunc | undefined => {
7
  return (
306✔
8
    mock.getMockImplementation() ?? getTinyspyInternals(mock)?.getOriginal()
585✔
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✔
27
  mock: MockInstance<TFunc>,
28
): TinyspyInternals<TFunc> | undefined => {
29
  const maybeTinyspy = mock as unknown as Record<PropertyKey, unknown>
279✔
30

31
  for (const key of Object.getOwnPropertySymbols(maybeTinyspy)) {
279✔
32
    const maybeTinyspyInternals = maybeTinyspy[key]
279✔
33

34
    if (
279!
35
      maybeTinyspyInternals &&
1,116✔
36
      typeof maybeTinyspyInternals === 'object' &&
37
      'getOriginal' in maybeTinyspyInternals &&
38
      typeof maybeTinyspyInternals.getOriginal === 'function'
39
    ) {
40
      return maybeTinyspyInternals as TinyspyInternals<TFunc>
279✔
41
    }
42
  }
43

NEW
44
  return undefined
×
45
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc