@vitest-agent/mcp 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +1 -2
  2. package/index.d.ts +2 -2
  3. package/index.js +1 -1
  4. package/package.json +1 -1
  5. package/server.js +2 -4
  6. package/patterns/_meta.json +0 -67
  7. package/patterns/authoring-a-custom-vitest-agent-reporter.md +0 -82
  8. package/patterns/known-issues-and-caveats.md +0 -52
  9. package/patterns/operating-vitest-agent-as-an-agent.md +0 -62
  10. package/patterns/running-tests-via-mcp.md +0 -103
  11. package/patterns/silencing-leaking-output-in-tests.md +0 -91
  12. package/patterns/testing-effect-schema-definitions.md +0 -71
  13. package/patterns/testing-effect-services-with-mock-layers.md +0 -63
  14. package/resources/index.js +0 -166
  15. package/resources/indexes.js +0 -77
  16. package/resources/manifest-schema.js +0 -46
  17. package/resources/paths.js +0 -20
  18. package/resources/patterns.js +0 -22
  19. package/resources/upstream-docs.js +0 -22
  20. package/vendor/vitest-docs/ATTRIBUTION.md +0 -5
  21. package/vendor/vitest-docs/api/advanced/artifacts.md +0 -189
  22. package/vendor/vitest-docs/api/advanced/metadata.md +0 -68
  23. package/vendor/vitest-docs/api/advanced/plugin.md +0 -168
  24. package/vendor/vitest-docs/api/advanced/reporters.md +0 -342
  25. package/vendor/vitest-docs/api/advanced/runner.md +0 -334
  26. package/vendor/vitest-docs/api/advanced/test-case.md +0 -302
  27. package/vendor/vitest-docs/api/advanced/test-collection.md +0 -89
  28. package/vendor/vitest-docs/api/advanced/test-module.md +0 -140
  29. package/vendor/vitest-docs/api/advanced/test-project.md +0 -321
  30. package/vendor/vitest-docs/api/advanced/test-specification.md +0 -96
  31. package/vendor/vitest-docs/api/advanced/test-suite.md +0 -230
  32. package/vendor/vitest-docs/api/advanced/vitest.md +0 -684
  33. package/vendor/vitest-docs/api/assert-type.md +0 -22
  34. package/vendor/vitest-docs/api/assert.md +0 -1960
  35. package/vendor/vitest-docs/api/browser/assertions.md +0 -1277
  36. package/vendor/vitest-docs/api/browser/commands.md +0 -154
  37. package/vendor/vitest-docs/api/browser/context.md +0 -338
  38. package/vendor/vitest-docs/api/browser/interactivity.md +0 -681
  39. package/vendor/vitest-docs/api/browser/locators.md +0 -1171
  40. package/vendor/vitest-docs/api/browser/react.md +0 -346
  41. package/vendor/vitest-docs/api/browser/svelte.md +0 -292
  42. package/vendor/vitest-docs/api/browser/vue.md +0 -222
  43. package/vendor/vitest-docs/api/describe.md +0 -374
  44. package/vendor/vitest-docs/api/expect-typeof.md +0 -571
  45. package/vendor/vitest-docs/api/expect.md +0 -2304
  46. package/vendor/vitest-docs/api/hooks.md +0 -463
  47. package/vendor/vitest-docs/api/mock.md +0 -701
  48. package/vendor/vitest-docs/api/test.md +0 -926
  49. package/vendor/vitest-docs/api/vi.md +0 -1372
  50. package/vendor/vitest-docs/config/alias.md +0 -13
  51. package/vendor/vitest-docs/config/allowonly.md +0 -32
  52. package/vendor/vitest-docs/config/api.md +0 -27
  53. package/vendor/vitest-docs/config/attachmentsdir.md +0 -6
  54. package/vendor/vitest-docs/config/bail.md +0 -9
  55. package/vendor/vitest-docs/config/benchmark.md +0 -65
  56. package/vendor/vitest-docs/config/browser/api.md +0 -23
  57. package/vendor/vitest-docs/config/browser/commands.md +0 -6
  58. package/vendor/vitest-docs/config/browser/connecttimeout.md +0 -10
  59. package/vendor/vitest-docs/config/browser/detailspanelposition.md +0 -38
  60. package/vendor/vitest-docs/config/browser/enabled.md +0 -40
  61. package/vendor/vitest-docs/config/browser/expect.md +0 -250
  62. package/vendor/vitest-docs/config/browser/headless.md +0 -7
  63. package/vendor/vitest-docs/config/browser/instances.md +0 -47
  64. package/vendor/vitest-docs/config/browser/isolate.md +0 -11
  65. package/vendor/vitest-docs/config/browser/locators.md +0 -24
  66. package/vendor/vitest-docs/config/browser/orchestratorscripts.md +0 -39
  67. package/vendor/vitest-docs/config/browser/playwright.md +0 -214
  68. package/vendor/vitest-docs/config/browser/preview.md +0 -32
  69. package/vendor/vitest-docs/config/browser/provider.md +0 -79
  70. package/vendor/vitest-docs/config/browser/screenshotdirectory.md +0 -6
  71. package/vendor/vitest-docs/config/browser/screenshotfailures.md +0 -6
  72. package/vendor/vitest-docs/config/browser/testerhtmlpath.md +0 -5
  73. package/vendor/vitest-docs/config/browser/trace.md +0 -43
  74. package/vendor/vitest-docs/config/browser/trackunhandlederrors.md +0 -10
  75. package/vendor/vitest-docs/config/browser/ui.md +0 -7
  76. package/vendor/vitest-docs/config/browser/viewport.md +0 -6
  77. package/vendor/vitest-docs/config/browser/webdriverio.md +0 -64
  78. package/vendor/vitest-docs/config/cache.md +0 -26
  79. package/vendor/vitest-docs/config/chaiconfig.md +0 -29
  80. package/vendor/vitest-docs/config/clearmocks.md +0 -22
  81. package/vendor/vitest-docs/config/coverage.md +0 -455
  82. package/vendor/vitest-docs/config/css.md +0 -47
  83. package/vendor/vitest-docs/config/dangerouslyignoreunhandlederrors.md +0 -23
  84. package/vendor/vitest-docs/config/deps.md +0 -127
  85. package/vendor/vitest-docs/config/detectasyncleaks.md +0 -39
  86. package/vendor/vitest-docs/config/diff.md +0 -96
  87. package/vendor/vitest-docs/config/dir.md +0 -7
  88. package/vendor/vitest-docs/config/disableconsoleintercept.md +0 -15
  89. package/vendor/vitest-docs/config/env.md +0 -5
  90. package/vendor/vitest-docs/config/environment.md +0 -96
  91. package/vendor/vitest-docs/config/environmentoptions.md +0 -30
  92. package/vendor/vitest-docs/config/exclude.md +0 -49
  93. package/vendor/vitest-docs/config/execargv.md +0 -10
  94. package/vendor/vitest-docs/config/expandsnapshotdiff.md +0 -7
  95. package/vendor/vitest-docs/config/expect.md +0 -38
  96. package/vendor/vitest-docs/config/experimental.md +0 -510
  97. package/vendor/vitest-docs/config/faketimers.md +0 -51
  98. package/vendor/vitest-docs/config/fileparallelism.md +0 -11
  99. package/vendor/vitest-docs/config/forcereruntriggers.md +0 -19
  100. package/vendor/vitest-docs/config/globals.md +0 -42
  101. package/vendor/vitest-docs/config/globalsetup.md +0 -72
  102. package/vendor/vitest-docs/config/hideskippedtests.md +0 -7
  103. package/vendor/vitest-docs/config/hooktimeout.md +0 -7
  104. package/vendor/vitest-docs/config/include-source.md +0 -115
  105. package/vendor/vitest-docs/config/include.md +0 -71
  106. package/vendor/vitest-docs/config/includetasklocation.md +0 -17
  107. package/vendor/vitest-docs/config/index.md +0 -85
  108. package/vendor/vitest-docs/config/isolate.md +0 -13
  109. package/vendor/vitest-docs/config/logheapusage.md +0 -7
  110. package/vendor/vitest-docs/config/maxconcurrency.md +0 -9
  111. package/vendor/vitest-docs/config/maxworkers.md +0 -49
  112. package/vendor/vitest-docs/config/mockreset.md +0 -22
  113. package/vendor/vitest-docs/config/mode.md +0 -7
  114. package/vendor/vitest-docs/config/name.md +0 -111
  115. package/vendor/vitest-docs/config/onconsolelog.md +0 -25
  116. package/vendor/vitest-docs/config/onstacktrace.md +0 -32
  117. package/vendor/vitest-docs/config/onunhandlederror.md +0 -35
  118. package/vendor/vitest-docs/config/open.md +0 -7
  119. package/vendor/vitest-docs/config/outputfile.md +0 -7
  120. package/vendor/vitest-docs/config/passwithnotests.md +0 -7
  121. package/vendor/vitest-docs/config/pool.md +0 -45
  122. package/vendor/vitest-docs/config/printconsoletrace.md +0 -6
  123. package/vendor/vitest-docs/config/projects.md +0 -6
  124. package/vendor/vitest-docs/config/provide.md +0 -45
  125. package/vendor/vitest-docs/config/reporters.md +0 -69
  126. package/vendor/vitest-docs/config/resolvesnapshotpath.md +0 -36
  127. package/vendor/vitest-docs/config/restoremocks.md +0 -22
  128. package/vendor/vitest-docs/config/retry.md +0 -140
  129. package/vendor/vitest-docs/config/root.md +0 -6
  130. package/vendor/vitest-docs/config/runner.md +0 -6
  131. package/vendor/vitest-docs/config/sequence.md +0 -158
  132. package/vendor/vitest-docs/config/server.md +0 -68
  133. package/vendor/vitest-docs/config/setupfiles.md +0 -40
  134. package/vendor/vitest-docs/config/silent.md +0 -9
  135. package/vendor/vitest-docs/config/slowtestthreshold.md +0 -7
  136. package/vendor/vitest-docs/config/snapshotenvironment.md +0 -27
  137. package/vendor/vitest-docs/config/snapshotformat.md +0 -28
  138. package/vendor/vitest-docs/config/snapshotserializers.md +0 -6
  139. package/vendor/vitest-docs/config/stricttags.md +0 -30
  140. package/vendor/vitest-docs/config/tags.md +0 -141
  141. package/vendor/vitest-docs/config/teardowntimeout.md +0 -7
  142. package/vendor/vitest-docs/config/testnamepattern.md +0 -21
  143. package/vendor/vitest-docs/config/testtimeout.md +0 -7
  144. package/vendor/vitest-docs/config/typecheck.md +0 -77
  145. package/vendor/vitest-docs/config/ui.md +0 -15
  146. package/vendor/vitest-docs/config/unstubenvs.md +0 -20
  147. package/vendor/vitest-docs/config/unstubglobals.md +0 -20
  148. package/vendor/vitest-docs/config/update.md +0 -16
  149. package/vendor/vitest-docs/config/vmmemorylimit.md +0 -30
  150. package/vendor/vitest-docs/config/watch.md +0 -11
  151. package/vendor/vitest-docs/config/watchtriggerpatterns.md +0 -29
  152. package/vendor/vitest-docs/guide/advanced/index.md +0 -147
  153. package/vendor/vitest-docs/guide/advanced/pool.md +0 -148
  154. package/vendor/vitest-docs/guide/advanced/reporters.md +0 -93
  155. package/vendor/vitest-docs/guide/advanced/tests.md +0 -125
  156. package/vendor/vitest-docs/guide/browser/aria-snapshots.md +0 -470
  157. package/vendor/vitest-docs/guide/browser/component-testing.md +0 -571
  158. package/vendor/vitest-docs/guide/browser/index.md +0 -630
  159. package/vendor/vitest-docs/guide/browser/multiple-setups.md +0 -121
  160. package/vendor/vitest-docs/guide/browser/trace-view.md +0 -126
  161. package/vendor/vitest-docs/guide/browser/visual-regression-testing.md +0 -734
  162. package/vendor/vitest-docs/guide/cli-generated.md +0 -972
  163. package/vendor/vitest-docs/guide/cli.md +0 -234
  164. package/vendor/vitest-docs/guide/common-errors.md +0 -163
  165. package/vendor/vitest-docs/guide/coverage.md +0 -515
  166. package/vendor/vitest-docs/guide/debugging.md +0 -127
  167. package/vendor/vitest-docs/guide/environment.md +0 -101
  168. package/vendor/vitest-docs/guide/extending-matchers.md +0 -160
  169. package/vendor/vitest-docs/guide/features.md +0 -310
  170. package/vendor/vitest-docs/guide/filtering.md +0 -175
  171. package/vendor/vitest-docs/guide/ide.md +0 -43
  172. package/vendor/vitest-docs/guide/improving-performance.md +0 -245
  173. package/vendor/vitest-docs/guide/in-source.md +0 -159
  174. package/vendor/vitest-docs/guide/index.md +0 -128
  175. package/vendor/vitest-docs/guide/learn/async.md +0 -147
  176. package/vendor/vitest-docs/guide/learn/debugging-tests.md +0 -210
  177. package/vendor/vitest-docs/guide/learn/matchers.md +0 -277
  178. package/vendor/vitest-docs/guide/learn/mock-functions.md +0 -277
  179. package/vendor/vitest-docs/guide/learn/setup-teardown.md +0 -240
  180. package/vendor/vitest-docs/guide/learn/snapshots.md +0 -166
  181. package/vendor/vitest-docs/guide/learn/testing-in-practice.md +0 -430
  182. package/vendor/vitest-docs/guide/learn/writing-tests-with-ai.md +0 -127
  183. package/vendor/vitest-docs/guide/learn/writing-tests.md +0 -231
  184. package/vendor/vitest-docs/guide/lifecycle.md +0 -379
  185. package/vendor/vitest-docs/guide/migration.md +0 -863
  186. package/vendor/vitest-docs/guide/mocking/classes.md +0 -158
  187. package/vendor/vitest-docs/guide/mocking/dates.md +0 -52
  188. package/vendor/vitest-docs/guide/mocking/file-system.md +0 -74
  189. package/vendor/vitest-docs/guide/mocking/functions.md +0 -61
  190. package/vendor/vitest-docs/guide/mocking/globals.md +0 -20
  191. package/vendor/vitest-docs/guide/mocking/modules.md +0 -414
  192. package/vendor/vitest-docs/guide/mocking/requests.md +0 -114
  193. package/vendor/vitest-docs/guide/mocking/timers.md +0 -48
  194. package/vendor/vitest-docs/guide/mocking.md +0 -239
  195. package/vendor/vitest-docs/guide/open-telemetry.md +0 -156
  196. package/vendor/vitest-docs/guide/parallelism.md +0 -82
  197. package/vendor/vitest-docs/guide/profiling-test-performance.md +0 -243
  198. package/vendor/vitest-docs/guide/projects.md +0 -291
  199. package/vendor/vitest-docs/guide/recipes.md +0 -59
  200. package/vendor/vitest-docs/guide/reporters.md +0 -723
  201. package/vendor/vitest-docs/guide/snapshot.md +0 -620
  202. package/vendor/vitest-docs/guide/test-annotations.md +0 -103
  203. package/vendor/vitest-docs/guide/test-context.md +0 -902
  204. package/vendor/vitest-docs/guide/test-tags.md +0 -314
  205. package/vendor/vitest-docs/guide/testing-types.md +0 -149
  206. package/vendor/vitest-docs/guide/ui.md +0 -160
  207. package/vendor/vitest-docs/guide/using-plugins.md +0 -5
  208. package/vendor/vitest-docs/manifest.json +0 -1691
@@ -1,701 +0,0 @@
1
- # Mocks
2
-
3
- You can create a mock function or a class to track its execution with the `vi.fn` method. If you want to track a property on an already created object, you can use the `vi.spyOn` method:
4
-
5
- ```js
6
- import { vi } from 'vitest'
7
-
8
- const fn = vi.fn()
9
- fn('hello world')
10
- fn.mock.calls[0] === ['hello world']
11
-
12
- const market = {
13
- getApples: () => 100
14
- }
15
-
16
- const getApplesSpy = vi.spyOn(market, 'getApples')
17
- market.getApples()
18
- getApplesSpy.mock.calls.length === 1
19
- ```
20
-
21
- You should use mock assertions (e.g., [`toHaveBeenCalled`](/api/expect#tohavebeencalled)) on [`expect`](/api/expect) to assert mock results. This API reference describes available properties and methods to manipulate mock behavior.
22
-
23
- ::: warning IMPORTANT
24
- Vitest spies inherit implementation's [`length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) property when initialized, but it doesn't override it if the implementation was changed later:
25
-
26
- ::: code-group
27
- ```ts [vi.fn]
28
- const fn = vi.fn((arg1) => {})
29
- fn.length // == 1
30
-
31
- fn.mockImplementation(() => {})
32
- fn.length // == 1
33
- ```
34
- ```ts [vi.spyOn]
35
- const example = {
36
- fn(arg1, arg2) {
37
- // ...
38
- }
39
- }
40
-
41
- const fn = vi.spyOn(example, 'fn')
42
- fn.length // == 2
43
-
44
- fn.mockImplementation(() => {})
45
- fn.length // == 2
46
- ```
47
- :::
48
-
49
- ::: tip
50
- The custom function implementation in the types below is marked with a generic `<T>`.
51
- :::
52
-
53
- ::: warning Class Support {#class-support}
54
- Shorthand methods like `mockReturnValue`, `mockReturnValueOnce`, `mockResolvedValue` and others cannot be used on a mocked class. Class constructors have [unintuitive behaviour](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) regarding the return value:
55
-
56
- ```ts {2,7}
57
- const CorrectDogClass = vi.fn(class {
58
- constructor(public name: string) {}
59
- })
60
-
61
- const IncorrectDogClass = vi.fn(class {
62
- constructor(public name: string) {
63
- return { name }
64
- }
65
- })
66
-
67
- const Marti = new CorrectDogClass('Marti')
68
- const Newt = new IncorrectDogClass('Newt')
69
-
70
- Marti instanceof CorrectDogClass // ✅ true
71
- Newt instanceof IncorrectDogClass // ❌ false!
72
- ```
73
-
74
- Even though the shapes are the same, the _return value_ from the constructor is assigned to `Newt`, which is a plain object, not an instance of a mock. Vitest guards you against this behaviour in shorthand methods (but not in `mockImplementation`!) and throws an error instead.
75
-
76
- If you need to mock constructed instance of a class, consider using the `class` syntax with `mockImplementation` instead:
77
-
78
- ```ts
79
- mock.mockReturnValue({ hello: () => 'world' }) // [!code --]
80
- mock.mockImplementation(class { hello = () => 'world' }) // [!code ++]
81
- ```
82
-
83
- If you need to test the behaviour where this is a valid use case, you can use `mockImplementation` with a `constructor`:
84
-
85
- ```ts
86
- mock.mockImplementation(class {
87
- constructor(name: string) {
88
- return { name }
89
- }
90
- })
91
- ```
92
- :::
93
-
94
- ## getMockImplementation
95
-
96
- ```ts
97
- function getMockImplementation(): T | undefined
98
- ```
99
-
100
- Returns the current mock implementation if there is one.
101
-
102
- If the mock was created with [`vi.fn`](/api/vi#vi-fn), it will use the provided method as the mock implementation.
103
-
104
- If the mock was created with [`vi.spyOn`](/api/vi#vi-spyon), it will return `undefined` unless a custom implementation is provided.
105
-
106
- ## getMockName
107
-
108
- ```ts
109
- function getMockName(): string
110
- ```
111
-
112
- Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, `vi.fn()` mocks will return `'vi.fn()'`, while spies created with `vi.spyOn` will keep the original name.
113
-
114
- ## mockClear
115
-
116
- ```ts
117
- function mockClear(): Mock<T>
118
- ```
119
-
120
- Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions.
121
-
122
- ```ts
123
- const person = {
124
- greet: (name: string) => `Hello ${name}`,
125
- }
126
- const spy = vi.spyOn(person, 'greet').mockImplementation(() => 'mocked')
127
- expect(person.greet('Alice')).toBe('mocked')
128
- expect(spy.mock.calls).toEqual([['Alice']])
129
-
130
- // clear call history but keep mock implementation
131
- spy.mockClear()
132
- expect(spy.mock.calls).toEqual([])
133
- expect(person.greet('Bob')).toBe('mocked')
134
- expect(spy.mock.calls).toEqual([['Bob']])
135
- ```
136
-
137
- To automatically call this method before each test, enable the [`clearMocks`](/config/clearmocks) setting in the configuration.
138
-
139
- ## mockName
140
-
141
- ```ts
142
- function mockName(name: string): Mock<T>
143
- ```
144
-
145
- Sets the internal mock name. This is useful for identifying the mock when an assertion fails.
146
-
147
- ## mockImplementation
148
-
149
- ```ts
150
- function mockImplementation(fn: T): Mock<T>
151
- ```
152
-
153
- Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function.
154
-
155
- ```ts
156
- const mockFn = vi.fn().mockImplementation((apples: number) => apples + 1)
157
- // or: vi.fn(apples => apples + 1);
158
-
159
- const NelliesBucket = mockFn(0)
160
- const BobsBucket = mockFn(1)
161
-
162
- NelliesBucket === 1 // true
163
- BobsBucket === 2 // true
164
-
165
- mockFn.mock.calls[0][0] === 0 // true
166
- mockFn.mock.calls[1][0] === 1 // true
167
- ```
168
-
169
- ## mockImplementationOnce
170
-
171
- ```ts
172
- function mockImplementationOnce(fn: T): Mock<T>
173
- ```
174
-
175
- Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. This method can be chained to produce different results for multiple function calls.
176
-
177
- ```ts
178
- const myMockFn = vi
179
- .fn()
180
- .mockImplementationOnce(() => true) // 1st call
181
- .mockImplementationOnce(() => false) // 2nd call
182
-
183
- myMockFn() // 1st call: true
184
- myMockFn() // 2nd call: false
185
- ```
186
-
187
- When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called:
188
-
189
- ```ts
190
- const myMockFn = vi
191
- .fn(() => 'default')
192
- .mockImplementationOnce(() => 'first call')
193
- .mockImplementationOnce(() => 'second call')
194
-
195
- // 'first call', 'second call', 'default', 'default'
196
- console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn())
197
- ```
198
-
199
- ## withImplementation
200
-
201
- ```ts
202
- function withImplementation(
203
- fn: T,
204
- cb: () => void
205
- ): Mock<T>
206
- function withImplementation(
207
- fn: T,
208
- cb: () => Promise<void>
209
- ): Promise<Mock<T>>
210
- ```
211
-
212
- Overrides the original mock implementation temporarily while the callback is being executed.
213
-
214
- ```js
215
- const myMockFn = vi.fn(() => 'original')
216
-
217
- myMockFn.withImplementation(() => 'temp', () => {
218
- myMockFn() // 'temp'
219
- })
220
-
221
- myMockFn() // 'original'
222
- ```
223
-
224
- Can be used with an asynchronous callback. The method has to be awaited to use the original implementation afterward.
225
-
226
- ```ts
227
- test('async callback', () => {
228
- const myMockFn = vi.fn(() => 'original')
229
-
230
- // We await this call since the callback is async
231
- await myMockFn.withImplementation(
232
- () => 'temp',
233
- async () => {
234
- myMockFn() // 'temp'
235
- },
236
- )
237
-
238
- myMockFn() // 'original'
239
- })
240
- ```
241
-
242
- Note that this method takes precedence over the [`mockImplementationOnce`](#mockimplementationonce).
243
-
244
- ## mockRejectedValue
245
-
246
- ```ts
247
- function mockRejectedValue(value: unknown): Mock<T>
248
- ```
249
-
250
- Accepts an error that will be rejected when an async function is called.
251
-
252
- ```ts
253
- const asyncMock = vi.fn().mockRejectedValue(new Error('Async error'))
254
-
255
- await asyncMock() // throws Error<'Async error'>
256
- ```
257
-
258
- ## mockRejectedValueOnce
259
-
260
- ```ts
261
- function mockRejectedValueOnce(value: unknown): Mock<T>
262
- ```
263
-
264
- Accepts a value that will be rejected during the next function call. If chained, each consecutive call will reject the specified value.
265
-
266
- ```ts
267
- const asyncMock = vi
268
- .fn()
269
- .mockResolvedValueOnce('first call')
270
- .mockRejectedValueOnce(new Error('Async error'))
271
-
272
- await asyncMock() // 'first call'
273
- await asyncMock() // throws Error<'Async error'>
274
- ```
275
-
276
- ## mockReset
277
-
278
- ```ts
279
- function mockReset(): Mock<T>
280
- ```
281
-
282
- Does what [`mockClear`](#mockClear) does and resets the mock implementation. This also resets all "once" implementations.
283
-
284
- Note that resetting a mock from `vi.fn()` will set the implementation to an empty function that returns `undefined`.
285
- Resetting a mock from `vi.fn(impl)` will reset the implementation to `impl`.
286
-
287
- This is useful when you want to reset a mock to its original state.
288
-
289
- ```ts
290
- const person = {
291
- greet: (name: string) => `Hello ${name}`,
292
- }
293
- const spy = vi.spyOn(person, 'greet').mockImplementation(() => 'mocked')
294
- expect(person.greet('Alice')).toBe('mocked')
295
- expect(spy.mock.calls).toEqual([['Alice']])
296
-
297
- // clear call history and reset implementation, but method is still spied
298
- spy.mockReset()
299
- expect(spy.mock.calls).toEqual([])
300
- expect(person.greet).toBe(spy)
301
- expect(person.greet('Bob')).toBe('Hello Bob')
302
- expect(spy.mock.calls).toEqual([['Bob']])
303
- ```
304
-
305
- To automatically call this method before each test, enable the [`mockReset`](/config/mockreset) setting in the configuration.
306
-
307
- ## mockRestore
308
-
309
- ```ts
310
- function mockRestore(): Mock<T>
311
- ```
312
-
313
- Does what [`mockReset`](#mockreset) does and restores the original descriptors of spied-on objects, if the mock was created with [`vi.spyOn`](/api/vi#vi-spyon).
314
-
315
- `mockRestore` on a `vi.fn()` mock is identical to [`mockReset`](#mockreset).
316
-
317
- ```ts
318
- const person = {
319
- greet: (name: string) => `Hello ${name}`,
320
- }
321
- const spy = vi.spyOn(person, 'greet').mockImplementation(() => 'mocked')
322
- expect(person.greet('Alice')).toBe('mocked')
323
- expect(spy.mock.calls).toEqual([['Alice']])
324
-
325
- // clear call history and restore spied object method
326
- spy.mockRestore()
327
- expect(spy.mock.calls).toEqual([])
328
- expect(person.greet).not.toBe(spy)
329
- expect(person.greet('Bob')).toBe('Hello Bob')
330
- expect(spy.mock.calls).toEqual([])
331
- ```
332
-
333
- To automatically call this method before each test, enable the [`restoreMocks`](/config/restoremocks) setting in the configuration.
334
-
335
- ## mockResolvedValue
336
-
337
- ```ts
338
- function mockResolvedValue(value: Awaited<ReturnType<T>>): Mock<T>
339
- ```
340
-
341
- Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function.
342
-
343
- ```ts
344
- const asyncMock = vi.fn().mockResolvedValue(42)
345
-
346
- await asyncMock() // 42
347
- ```
348
-
349
- ## mockResolvedValueOnce
350
-
351
- ```ts
352
- function mockResolvedValueOnce(value: Awaited<ReturnType<T>>): Mock<T>
353
- ```
354
-
355
- Accepts a value that will be resolved during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value.
356
-
357
- ```ts
358
- const asyncMock = vi
359
- .fn()
360
- .mockResolvedValue('default')
361
- .mockResolvedValueOnce('first call')
362
- .mockResolvedValueOnce('second call')
363
-
364
- await asyncMock() // first call
365
- await asyncMock() // second call
366
- await asyncMock() // default
367
- await asyncMock() // default
368
- ```
369
-
370
- ## mockReturnThis
371
-
372
- ```ts
373
- function mockReturnThis(): Mock<T>
374
- ```
375
-
376
- Use this if you need to return the `this` context from the method without invoking the actual implementation. This is a shorthand for:
377
-
378
- ```ts
379
- spy.mockImplementation(function () {
380
- return this
381
- })
382
- ```
383
-
384
- ## mockReturnValue
385
-
386
- ```ts
387
- function mockReturnValue(value: ReturnType<T>): Mock<T>
388
- ```
389
-
390
- Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.
391
-
392
- ```ts
393
- const mock = vi.fn()
394
- mock.mockReturnValue(42)
395
- mock() // 42
396
- mock.mockReturnValue(43)
397
- mock() // 43
398
- ```
399
-
400
- ## mockReturnValueOnce
401
-
402
- ```ts
403
- function mockReturnValueOnce(value: ReturnType<T>): Mock<T>
404
- ```
405
-
406
- Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.
407
-
408
- When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called:
409
-
410
- ```ts
411
- const myMockFn = vi
412
- .fn()
413
- .mockReturnValue('default')
414
- .mockReturnValueOnce('first call')
415
- .mockReturnValueOnce('second call')
416
-
417
- // 'first call', 'second call', 'default', 'default'
418
- console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn())
419
- ```
420
-
421
- ## mockThrow <Version>4.1.0</Version> {#mockthrow}
422
-
423
- ```ts
424
- function mockThrow(value: unknown): Mock<T>
425
- ```
426
-
427
- Accepts a value that will be thrown whenever the mock function is called.
428
-
429
- ```ts
430
- const myMockFn = vi.fn()
431
- myMockFn.mockThrow(new Error('error message'))
432
- myMockFn() // throws Error<'error message'>
433
- ```
434
-
435
- ## mockThrowOnce <Version>4.1.0</Version> {#mockthrowonce}
436
-
437
- ```ts
438
- function mockThrowOnce(value: unknown): Mock<T>
439
- ```
440
-
441
- Accepts a value that will be thrown during the next function call. If chained, every consecutive call will throw the specified value.
442
-
443
- ```ts
444
- const myMockFn = vi
445
- .fn()
446
- .mockReturnValue('default')
447
- .mockThrowOnce(new Error('first call error'))
448
- .mockThrowOnce('second call error')
449
-
450
- expect(() => myMockFn()).toThrow('first call error')
451
- expect(() => myMockFn()).toThrow('second call error')
452
- expect(myMockFn()).toEqual('default')
453
- ```
454
-
455
- ## mock.calls
456
-
457
- ```ts
458
- const calls: Parameters<T>[]
459
- ```
460
-
461
- This is an array containing all arguments for each call. One item of the array is the arguments of that call.
462
-
463
- ```js
464
- const fn = vi.fn()
465
-
466
- fn('arg1', 'arg2')
467
- fn('arg3')
468
-
469
- fn.mock.calls === [
470
- ['arg1', 'arg2'], // first call
471
- ['arg3'], // second call
472
- ]
473
- ```
474
-
475
- :::warning Objects are Stored by Reference
476
- Note that Vitest always stores objects by reference in all properties of the `mock` state. This means that if the properties were changed by your code, then some assertions like [`.toHaveBeenCalledWith`](/api/expect#tohavebeencalledwith) will not pass:
477
-
478
- ```ts
479
- const argument = {
480
- value: 0,
481
- }
482
- const fn = vi.fn()
483
- fn(argument) // { value: 0 }
484
-
485
- argument.value = 10
486
-
487
- expect(fn).toHaveBeenCalledWith({ value: 0 }) // [!code --]
488
-
489
- // The equality check is done against the original argument,
490
- // but its property was changed between the call and assertion
491
- expect(fn).toHaveBeenCalledWith({ value: 10 }) // [!code ++]
492
- ```
493
-
494
- In this case you can clone the argument yourself:
495
-
496
- ```ts{6}
497
- const calledArguments = []
498
- const fn = vi.fn((arg) => {
499
- calledArguments.push(structuredClone(arg))
500
- })
501
-
502
- expect(calledArguments[0]).toEqual({ value: 0 })
503
- ```
504
- :::
505
-
506
- ## mock.lastCall
507
-
508
- ```ts
509
- const lastCall: Parameters<T> | undefined
510
- ```
511
-
512
- This contains the arguments of the last call. If the mock wasn't called, it will return `undefined`.
513
-
514
- ## mock.results
515
-
516
- ```ts
517
- interface MockResultReturn<T> {
518
- type: 'return'
519
- /**
520
- * The value that was returned from the function.
521
- * If the function returned a Promise, then this will be a resolved value.
522
- */
523
- value: T
524
- }
525
-
526
- interface MockResultIncomplete {
527
- type: 'incomplete'
528
- value: undefined
529
- }
530
-
531
- interface MockResultThrow {
532
- type: 'throw'
533
- /**
534
- * An error that was thrown during function execution.
535
- */
536
- value: any
537
- }
538
-
539
- type MockResult<T>
540
- = | MockResultReturn<T>
541
- | MockResultThrow
542
- | MockResultIncomplete
543
-
544
- const results: MockResult<ReturnType<T>>[]
545
- ```
546
-
547
- This is an array containing all values that were `returned` from the function. One item of the array is an object with properties `type` and `value`. Available types are:
548
-
549
- - `'return'` - function returned without throwing.
550
- - `'throw'` - function threw a value.
551
- - `'incomplete'` - the function did not finish running yet.
552
-
553
- The `value` property contains the returned value or thrown error. If the function returned a `Promise`, then `result` will always be `'return'` even if the promise was rejected.
554
-
555
- ```js
556
- const fn = vi.fn()
557
- .mockReturnValueOnce('result')
558
- .mockImplementationOnce(() => { throw new Error('thrown error') })
559
-
560
- const result = fn() // returned 'result'
561
-
562
- try {
563
- fn() // threw Error
564
- }
565
- catch {}
566
-
567
- fn.mock.results === [
568
- // first result
569
- {
570
- type: 'return',
571
- value: 'result',
572
- },
573
- // last result
574
- {
575
- type: 'throw',
576
- value: Error,
577
- },
578
- ]
579
- ```
580
-
581
- ## mock.settledResults
582
-
583
- ```ts
584
- interface MockSettledResultIncomplete {
585
- type: 'incomplete'
586
- value: undefined
587
- }
588
-
589
- interface MockSettledResultFulfilled<T> {
590
- type: 'fulfilled'
591
- value: T
592
- }
593
-
594
- interface MockSettledResultRejected {
595
- type: 'rejected'
596
- value: any
597
- }
598
-
599
- export type MockSettledResult<T>
600
- = | MockSettledResultFulfilled<T>
601
- | MockSettledResultRejected
602
- | MockSettledResultIncomplete
603
-
604
- const settledResults: MockSettledResult<Awaited<ReturnType<T>>>[]
605
- ```
606
-
607
- An array containing all values that were resolved or rejected by the function.
608
-
609
- If the function returned non-promise values, the `value` will be kept as is, but the `type` will still says `fulfilled` or `rejected`.
610
-
611
- Until the value is resolved or rejected, the `settledResult` type will be `incomplete`.
612
-
613
- ```js
614
- const fn = vi.fn().mockResolvedValueOnce('result')
615
-
616
- const result = fn()
617
-
618
- fn.mock.settledResults === [
619
- {
620
- type: 'incomplete',
621
- value: undefined,
622
- },
623
- ]
624
-
625
- await result
626
-
627
- fn.mock.settledResults === [
628
- {
629
- type: 'fulfilled',
630
- value: 'result',
631
- },
632
- ]
633
- ```
634
-
635
- ## mock.invocationCallOrder
636
-
637
- ```ts
638
- const invocationCallOrder: number[]
639
- ```
640
-
641
- This property returns the order of the mock function's execution. It is an array of numbers that are shared between all defined mocks.
642
-
643
- ```js
644
- const fn1 = vi.fn()
645
- const fn2 = vi.fn()
646
-
647
- fn1()
648
- fn2()
649
- fn1()
650
-
651
- fn1.mock.invocationCallOrder === [1, 3]
652
- fn2.mock.invocationCallOrder === [2]
653
- ```
654
-
655
- ## mock.contexts
656
-
657
- ```ts
658
- const contexts: ThisParameterType<T>[]
659
- ```
660
-
661
- This property is an array of `this` values used during each call to the mock function.
662
-
663
- ```js
664
- const fn = vi.fn()
665
- const context = {}
666
-
667
- fn.apply(context)
668
- fn.call(context)
669
-
670
- fn.mock.contexts[0] === context
671
- fn.mock.contexts[1] === context
672
- ```
673
-
674
- ## mock.instances
675
-
676
- ```ts
677
- const instances: ReturnType<T>[]
678
- ```
679
-
680
- This property is an array containing all instances that were created when the mock was called with the `new` keyword. Note that this is the actual context (`this`) of the function, not a return value.
681
-
682
- ::: warning
683
- If the mock was instantiated with `new MyClass()`, then `mock.instances` will be an array with one value:
684
-
685
- ```js
686
- const MyClass = vi.fn()
687
- const a = new MyClass()
688
-
689
- MyClass.mock.instances[0] === a
690
- ```
691
-
692
- If you return a value from the constructor, it will not be in the `instances` array, but instead inside `results`:
693
-
694
- ```js
695
- const Spy = vi.fn(() => ({ method: vi.fn() }))
696
- const a = new Spy()
697
-
698
- Spy.mock.instances[0] !== a
699
- Spy.mock.results[0] === a
700
- ```
701
- :::