MCPcopy
hub / github.com/vitest-dev/vitest / createMockInstance

Function createMockInstance

packages/spy/src/index.ts:30–242  ·  view source on GitHub ↗
(options: MockInstanceOption = {})

Source from the content-addressed store, hash-verified

28const MOCK_CONFIGS = new WeakMap<Mock<Procedure | Constructable>, MockConfig>()
29
30export function createMockInstance(options: MockInstanceOption = {}): Mock<Procedure | Constructable> {
31 const {
32 originalImplementation,
33 restore,
34 mockImplementation,
35 resetToMockImplementation,
36 resetToMockName,
37 } = options
38
39 if (restore) {
40 MOCK_RESTORE.add(restore)
41 }
42
43 const config = getDefaultConfig(originalImplementation)
44 const state = getDefaultState()
45
46 const mock = createMock({
47 config,
48 state,
49 ...options,
50 })
51 const mockLength = (mockImplementation || originalImplementation)?.length ?? 0
52 Object.defineProperty(mock, 'length', {
53 writable: true,
54 enumerable: false,
55 value: mockLength,
56 configurable: true,
57 })
58 // inherit the default name so it appears in snapshots and logs
59 // this is used by `vi.spyOn()` for better debugging.
60 // when `vi.fn()` is called, we just use the default string
61 if (resetToMockName) {
62 config.mockName = mock.name || 'vi.fn()'
63 }
64 MOCK_CONFIGS.set(mock, config)
65 REGISTERED_MOCKS.add(mock)
66
67 mock._isMockFunction = true
68 mock.getMockImplementation = () => {
69 // Jest only returns `config.mockImplementation` here,
70 // but we think it makes sense to return what the next function will be called
71 return config.onceMockImplementations[0] || config.mockImplementation
72 }
73
74 Object.defineProperty(mock, 'mock', {
75 configurable: false,
76 enumerable: true,
77 writable: false,
78 value: state,
79 })
80
81 mock.mockImplementation = function mockImplementation(implementation) {
82 config.mockImplementation = implementation
83 return mock
84 }
85
86 mock.mockImplementationOnce = function mockImplementationOnce(implementation) {
87 config.onceMockImplementations.push(implementation)

Callers 4

fnFunction · 0.85
spyOnFunction · 0.85
createMockFunction · 0.85
createMockFunction · 0.85

Calls 15

getDefaultConfigFunction · 0.85
getDefaultStateFunction · 0.85
resetFunction · 0.85
throwConstructorErrorFunction · 0.85
restoreFunction · 0.85
mockImplementationMethod · 0.80
mockClearMethod · 0.80
mockResetMethod · 0.80
mockRestoreMethod · 0.80
createMockFunction · 0.70
callbackFunction · 0.50

Tested by

no test coverage detected