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

Method register

packages/mocker/src/registry.ts:48–132  ·  view source on GitHub ↗
(
    typeOrEvent: MockedModuleType | MockedModuleSerialized,
    raw?: string,
    id?: string,
    url?: string,
    factoryOrRedirect?: string | (() => any),
  )

Source from the content-addressed store, hash-verified

46 url: string,
47 ): AutospiedModule
48 public register(
49 typeOrEvent: MockedModuleType | MockedModuleSerialized,
50 raw?: string,
51 id?: string,
52 url?: string,
53 factoryOrRedirect?: string | (() => any),
54 ): MockedModule {
55 const type = typeof typeOrEvent === 'object' ? typeOrEvent.type : typeOrEvent
56
57 if (typeof typeOrEvent === 'object') {
58 const event = typeOrEvent
59 if (
60 event instanceof AutomockedModule
61 || event instanceof AutospiedModule
62 || event instanceof ManualMockedModule
63 || event instanceof RedirectedModule
64 ) {
65 throw new TypeError(
66 `[vitest] Cannot register a mock that is already defined. `
67 + `Expected a JSON representation from \`MockedModule.toJSON\`, instead got "${event.type}". `
68 + `Use "registry.add()" to update a mock instead.`,
69 )
70 }
71 if (event.type === 'automock') {
72 const module = AutomockedModule.fromJSON(event)
73 this.add(module)
74 return module
75 }
76 else if (event.type === 'autospy') {
77 const module = AutospiedModule.fromJSON(event)
78 this.add(module)
79 return module
80 }
81 else if (event.type === 'redirect') {
82 const module = RedirectedModule.fromJSON(event)
83 this.add(module)
84 return module
85 }
86 else if (event.type === 'manual') {
87 throw new Error(`Cannot set serialized manual mock. Define a factory function manually with \`ManualMockedModule.fromJSON()\`.`)
88 }
89 else {
90 throw new Error(`Unknown mock type: ${(event as any).type}`)
91 }
92 }
93
94 if (typeof raw !== 'string') {
95 throw new TypeError('[vitest] Mocks require a raw string.')
96 }
97
98 if (typeof url !== 'string') {
99 throw new TypeError('[vitest] Mocks require a url string.')
100 }
101
102 if (typeof id !== 'string') {
103 throw new TypeError('[vitest] Mocks require an id string.')
104 }
105

Callers 4

registerMockFunction · 0.45
otel-browser.jsFile · 0.45

Calls 2

addMethod · 0.95
fromJSONMethod · 0.45

Tested by

no test coverage detected