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

Function createMock

packages/spy/src/index.ts:429–575  ·  view source on GitHub ↗
(
  {
    state,
    config,
    name: mockName,
    prototypeState,
    prototypeConfig,
    keepMembersImplementation,
    mockImplementation,
    prototypeMembers = [],
  }: MockInstanceOption & {
    state: MockContext
    config: MockConfig
  },
)

Source from the content-addressed store, hash-verified

427let invocationCallCounter = 1
428
429function createMock(
430 {
431 state,
432 config,
433 name: mockName,
434 prototypeState,
435 prototypeConfig,
436 keepMembersImplementation,
437 mockImplementation,
438 prototypeMembers = [],
439 }: MockInstanceOption & {
440 state: MockContext
441 config: MockConfig
442 },
443) {
444 const original = config.mockOriginal // init with vi.spyOn(obj, 'Klass')
445 const pseudoOriginal = mockImplementation // init with vi.fn(Klass)
446 const name = (mockName || original?.name || 'Mock') as string
447 const namedObject: Record<string, Mock<Procedure | Constructable>> = {
448 // to keep the name of the function intact
449 [name]: (function (this: any, ...args: any[]) {
450 registerCalls(args, state, prototypeState)
451 registerInvocationOrder(invocationCallCounter++, state, prototypeState)
452
453 const result = {
454 type: 'incomplete',
455 value: undefined,
456 } as MockResult<Procedure>
457
458 const settledResult = {
459 type: 'incomplete',
460 value: undefined,
461 } as MockSettledResult<Procedure>
462
463 registerResult(result, state, prototypeState)
464 registerSettledResult(settledResult, state, prototypeState)
465
466 const context = new.target ? undefined : this
467 const [instanceIndex, instancePrototypeIndex] = registerInstance(context, state, prototypeState)
468 const [contextIndex, contextPrototypeIndex] = registerContext(context, state, prototypeState)
469
470 const implementation: Procedure | Constructable
471 = config.onceMockImplementations.shift()
472 || config.mockImplementation
473 || prototypeConfig?.onceMockImplementations.shift()
474 || prototypeConfig?.mockImplementation
475 || original
476 || function () {}
477
478 let returnValue
479 let thrownValue
480 let didThrow = false
481
482 try {
483 if (new.target) {
484 returnValue = Reflect.construct(implementation, args, new.target)
485
486 // jest calls this before the implementation, but we have to resolve this _after_

Callers 1

createMockInstanceFunction · 0.70

Calls 12

registerCallsFunction · 0.85
registerInvocationOrderFunction · 0.85
registerResultFunction · 0.85
registerSettledResultFunction · 0.85
registerInstanceFunction · 0.85
registerContextFunction · 0.85
createMockInstanceFunction · 0.85
warnMethod · 0.80
getMockNameMethod · 0.80
isMockFunctionFunction · 0.70
getMethod · 0.45

Tested by

no test coverage detected