You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You should use mock assertions (e.g., [`toHaveBeenCalled`](/api/expect#tohavebeencalled)) on [`expect`](/api/expect) to assert mock result. This API reference describes available properties and methods to manipulate mock behavior.
22
22
23
+
::: tip
24
+
The custom function implementation in the types below is marked with a generic `<T>`.
25
+
:::
26
+
23
27
## getMockImplementation
24
28
25
-
-**Type:**`(...args: any) => any`
29
+
```ts
30
+
function getMockImplementation():T|undefined
31
+
```
26
32
27
33
Returnscurrentmockimplementationifthereisone.
28
34
29
-
If mock was created with [`vi.fn`](/api/vi#vi-fn), it will consider passed down method as a mock implementation.
Clears all information about every call. After calling it, all properties on `.mock` will return empty state. This method does not reset implementations. It is useful if you need to clean up mock between different assertions.
function mockImplementationOnce(fn: T): MockInstance<T>
91
+
```
76
92
77
-
Accepts a function that will be used as mock's implementation during the next call. Can be chained so that multiple function calls produce different results.
93
+
Acceptsafunctionto 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.
78
94
79
95
```ts
80
96
const myMockFn = vi
81
97
.fn()
82
-
.mockImplementationOnce(() =>true)
83
-
.mockImplementationOnce(() =>false)
98
+
.mockImplementationOnce(() => true) // 1st call
99
+
.mockImplementationOnce(() => false) // 2nd call
84
100
85
-
myMockFn() // true
86
-
myMockFn() // false
101
+
myMockFn() // 1st call: true
102
+
myMockFn() // 2nd call: false
87
103
```
88
104
89
-
When the mocked function runs out of implementations, it will invoke the default implementation that was set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called:
105
+
Whenthemockedfunction runs out of implementations, it will invoke the default implementation set with `vi.fn(() =>defaultValue)` or `.mockImplementation(() =>defaultValue)` if they were called:
function mockRejectedValueOnce(value: unknown): MockInstance<T>
180
+
```
153
181
154
-
Accepts a value that will be rejected during the next function call. If chained, every consecutive call will reject specified value.
182
+
Acceptsavaluethatwillberejectedduringthenextfunction call. If chained, each consecutive call will reject the specified value.
155
183
156
184
```ts
157
185
const asyncMock = vi
158
186
.fn()
159
187
.mockResolvedValueOnce('first call')
160
188
.mockRejectedValueOnce(new Error('Async error'))
161
189
162
-
awaitasyncMock() // first call
163
-
awaitasyncMock() // throws "Async error"
190
+
await asyncMock() // 'first call'
191
+
await asyncMock() // throws Error<'Async error'>
164
192
```
165
193
166
194
## mockReset
167
195
168
-
-**Type:**`() => MockInstance`
196
+
```ts
197
+
function mockReset(): MockInstance<T>
198
+
```
169
199
170
-
Does what `mockClear`does and makes inner implementation an empty function (returning `undefined` when invoked). This also resets all "once" implementations. This is useful when you want to completely reset a mock to the default state.
Note that restoring mock from `vi.fn()` will set implementation to an empty function that returns `undefined`. Restoring a `vi.fn(impl)` will restore implementation to `impl`.
212
+
Notethatrestoringamockcreatedwith`vi.fn()`willsettheimplementationtoanemptyfunction that returns `undefined`. Restoring a mock created with `vi.fn(impl)` will restore the implementation to `impl`.
181
213
182
-
If you want this method to be called before each test automatically, you can enable [`restoreMocks`](/config/#restoremocks) setting in config.
function mockResolvedValue(value: Awaited<ReturnType<T>>): MockInstance<T>
220
+
```
187
221
188
-
Accepts a value that will be resolved when async function is called.
222
+
Acceptsavaluethatwillberesolvedwhentheasyncfunction is called. TypeScript will only accept values that match the return type of the original function.
189
223
190
224
```ts
191
225
const asyncMock = vi.fn().mockResolvedValue(42)
@@ -195,9 +229,11 @@ await asyncMock() // 42
195
229
196
230
## mockResolvedValueOnce
197
231
198
-
-**Type:**`(value: any) => MockInstance`
232
+
```ts
233
+
function mockResolvedValueOnce(value: Awaited<ReturnType<T>>): MockInstance<T>
234
+
```
199
235
200
-
Accepts a value that will be resolved during the next function call. If chained, every consecutive call will resolve specified value.
236
+
Acceptsavaluethatwillberesolvedduringthenextfunction 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.
201
237
202
238
```ts
203
239
const asyncMock = vi
@@ -214,9 +250,11 @@ await asyncMock() // default
214
250
215
251
## mockReturnThis
216
252
217
-
-**Type:**`() => MockInstance`
253
+
```ts
254
+
function mockReturnThis(): MockInstance<T>
255
+
```
218
256
219
-
Use this if you need to return `this` context from the method without invoking actual implementation. This is a shorthand for:
function mockReturnValue(value: ReturnType<T>): MockInstance<T>
269
+
```
230
270
231
-
Accepts a value that will be returned whenever the mock function is called.
271
+
Acceptsavaluethatwillbereturnedwheneverthemockfunction is called. TypeScript will only accept values that match the return type of the original function.
232
272
233
273
```ts
234
274
const mock = vi.fn()
@@ -240,11 +280,13 @@ mock() // 43
240
280
241
281
## mockReturnValueOnce
242
282
243
-
-**Type:**`(value: any) => MockInstance`
283
+
```ts
284
+
function mockReturnValueOnce(value: ReturnType<T>): MockInstance<T>
285
+
```
244
286
245
-
Accepts a value that will be returned during the next function call. If chained, every consecutive call will return the specified value.
287
+
Acceptsavaluethatwillbereturnedwheneverthemockfunctionis called. TypeScript will only accept values that match the return type of the original function.
246
288
247
-
When there are no more `mockReturnValueOnce` values to use, mock will fallback to previously defined implementation if there is one.
289
+
Whenthemockedfunction runs out of implementations, it will invoke the default implementation set with `vi.fn(() =>defaultValue)` or `.mockImplementation(() =>defaultValue)` if they were called:
This contains the arguments of the last call. If mock wasn't called, will return `undefined`.
324
+
```ts
325
+
const lastCall: Parameters<T> | undefined
326
+
```
327
+
328
+
Thiscontainstheargumentsofthelastcall. Ifmockwasn't called, it will return `undefined`.
279
329
280
330
## mock.results
281
331
332
+
```ts
333
+
interface MockResultReturn<T> {
334
+
type: 'return'
335
+
/**
336
+
* The value that was returned from the function.
337
+
* If function returned a Promise, then this will be a resolved value.
338
+
*/
339
+
value: T
340
+
}
341
+
342
+
interface MockResultIncomplete {
343
+
type: 'incomplete'
344
+
value: undefined
345
+
}
346
+
347
+
interface MockResultThrow {
348
+
type: 'throw'
349
+
/**
350
+
* An error that was thrown during function execution.
351
+
*/
352
+
value: any
353
+
}
354
+
355
+
type MockResult<T> =
356
+
| MockResultReturn<T>
357
+
| MockResultThrow
358
+
| MockResultIncomplete
359
+
360
+
const results: MockResult<ReturnType<T>>[]
361
+
```
362
+
282
363
Thisisanarraycontainingallvaluesthatwere`returned`fromthefunction. One item of the array is an object with properties `type` and `value`. Available types are:
Thispropertyisanarraycontainingallinstancesthatwerecreatedwhenthemockwascalledwiththe`new`keyword. Notethatthisisanactualcontext (`this`) ofthefunction, not a return value.
0 commit comments