Skip to content

Commit 76169a1

Browse files
authored
docs: improve "Mock Functions" page (#6897)
1 parent 0ad2cdc commit 76169a1

File tree

2 files changed

+212
-73
lines changed

2 files changed

+212
-73
lines changed

docs/api/mock.md

Lines changed: 157 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -20,41 +20,55 @@ getApplesSpy.mock.calls.length === 1
2020

2121
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.
2222

23+
::: tip
24+
The custom function implementation in the types below is marked with a generic `<T>`.
25+
:::
26+
2327
## getMockImplementation
2428

25-
- **Type:** `(...args: any) => any`
29+
```ts
30+
function getMockImplementation(): T | undefined
31+
```
2632

2733
Returns current mock implementation if there is one.
2834

29-
If mock was created with [`vi.fn`](/api/vi#vi-fn), it will consider passed down method as a mock implementation.
35+
If the mock was created with [`vi.fn`](/api/vi#vi-fn), it will use the provided method as the mock implementation.
3036

31-
If mock was created with [`vi.spyOn`](/api/vi#vi-spyon), it will return `undefined` unless a custom implementation was provided.
37+
If the mock was created with [`vi.spyOn`](/api/vi#vi-spyon), it will return `undefined` unless a custom implementation is provided.
3238

3339
## getMockName
3440

35-
- **Type:** `() => string`
41+
```ts
42+
function getMockName(): string
43+
```
3644

37-
Use it to return the name given to mock with method `.mockName(name)`.
45+
Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, it will return `vi.fn()`.
3846

3947
## mockClear
4048

41-
- **Type:** `() => MockInstance`
49+
```ts
50+
function mockClear(): MockInstance<T>
51+
```
4252

43-
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.
53+
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.
4454

45-
If you want this method to be called before each test automatically, you can enable [`clearMocks`](/config/#clearmocks) setting in config.
55+
To automatically call this method before each test, enable the [`clearMocks`](/config/#clearmocks) setting in the configuration.
4656

4757
## mockName
4858

49-
- **Type:** `(name: string) => MockInstance`
59+
```ts
60+
function mockName(name: string): MockInstance<T>
61+
```
5062

51-
Sets internal mock name. Useful to see the name of the mock if assertion fails.
63+
Sets the internal mock name. This is useful for identifying the mock when an assertion fails.
5264

5365
## mockImplementation
5466

55-
- **Type:** `(fn: Function) => MockInstance`
67+
```ts
68+
function mockImplementation(fn: T): MockInstance<T>
69+
```
5670

57-
Accepts a function that will be used as an implementation of the mock.
71+
Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function.
5872

5973
```ts
6074
const mockFn = vi.fn().mockImplementation((apples: number) => apples + 1)
@@ -72,21 +86,23 @@ mockFn.mock.calls[1][0] === 1 // true
7286

7387
## mockImplementationOnce
7488

75-
- **Type:** `(fn: Function) => MockInstance`
89+
```ts
90+
function mockImplementationOnce(fn: T): MockInstance<T>
91+
```
7692

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+
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.
7894

7995
```ts
8096
const myMockFn = vi
8197
.fn()
82-
.mockImplementationOnce(() => true)
83-
.mockImplementationOnce(() => false)
98+
.mockImplementationOnce(() => true) // 1st call
99+
.mockImplementationOnce(() => false) // 2nd call
84100
85-
myMockFn() // true
86-
myMockFn() // false
101+
myMockFn() // 1st call: true
102+
myMockFn() // 2nd call: false
87103
```
88104

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+
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:
90106

91107
```ts
92108
const myMockFn = vi
@@ -100,8 +116,16 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn())
100116

101117
## withImplementation
102118

103-
- **Type:** `(fn: Function, callback: () => void) => MockInstance`
104-
- **Type:** `(fn: Function, callback: () => Promise<unknown>) => Promise<MockInstance>`
119+
```ts
120+
function withImplementation(
121+
fn: T,
122+
cb: () => void
123+
): MockInstance<T>
124+
function withImplementation(
125+
fn: T,
126+
cb: () => Promise<void>
127+
): Promise<MockInstance<T>>
128+
```
105129

106130
Overrides the original mock implementation temporarily while the callback is being executed.
107131

@@ -137,55 +161,65 @@ Note that this method takes precedence over the [`mockImplementationOnce`](#mock
137161

138162
## mockRejectedValue
139163

140-
- **Type:** `(value: any) => MockInstance`
164+
```ts
165+
function mockRejectedValue(value: unknown): MockInstance<T>
166+
```
141167

142168
Accepts an error that will be rejected when async function is called.
143169

144170
```ts
145171
const asyncMock = vi.fn().mockRejectedValue(new Error('Async error'))
146172
147-
await asyncMock() // throws "Async error"
173+
await asyncMock() // throws Error<'Async error'>
148174
```
149175

150176
## mockRejectedValueOnce
151177

152-
- **Type:** `(value: any) => MockInstance`
178+
```ts
179+
function mockRejectedValueOnce(value: unknown): MockInstance<T>
180+
```
153181

154-
Accepts a value that will be rejected during the next function call. If chained, every consecutive call will reject specified value.
182+
Accepts a value that will be rejected during the next function call. If chained, each consecutive call will reject the specified value.
155183

156184
```ts
157185
const asyncMock = vi
158186
.fn()
159187
.mockResolvedValueOnce('first call')
160188
.mockRejectedValueOnce(new Error('Async error'))
161189
162-
await asyncMock() // first call
163-
await asyncMock() // throws "Async error"
190+
await asyncMock() // 'first call'
191+
await asyncMock() // throws Error<'Async error'>
164192
```
165193

166194
## mockReset
167195

168-
- **Type:** `() => MockInstance`
196+
```ts
197+
function mockReset(): MockInstance<T>
198+
```
169199

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.
200+
Performs the same actions as `mockClear` and sets the inner implementation to an empty function (returning `undefined` when invoked). This also resets all "once" implementations. It is useful for completely resetting a mock to its default state.
171201

172-
If you want this method to be called before each test automatically, you can enable [`mockReset`](/config/#mockreset) setting in config.
202+
To automatically call this method before each test, enable the [`mockReset`](/config/#mockreset) setting in the configuration.
173203

174204
## mockRestore
175205

176-
- **Type:** `() => MockInstance`
206+
```ts
207+
function mockRestore(): MockInstance<T>
208+
```
177209

178-
Does what `mockReset` does and restores inner implementation to the original function.
210+
Performs the same actions as `mockReset` and restores the inner implementation to the original function.
179211

180-
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+
Note that restoring a mock created with `vi.fn()` will set the implementation to an empty function that returns `undefined`. Restoring a mock created with `vi.fn(impl)` will restore the implementation to `impl`.
181213

182-
If you want this method to be called before each test automatically, you can enable [`restoreMocks`](/config/#restoremocks) setting in config.
214+
To automatically call this method before each test, enable the [`restoreMocks`](/config/#restoremocks) setting in the configuration.
183215

184216
## mockResolvedValue
185217

186-
- **Type:** `(value: any) => MockInstance`
218+
```ts
219+
function mockResolvedValue(value: Awaited<ReturnType<T>>): MockInstance<T>
220+
```
187221

188-
Accepts a value that will be resolved when async function is called.
222+
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.
189223

190224
```ts
191225
const asyncMock = vi.fn().mockResolvedValue(42)
@@ -195,9 +229,11 @@ await asyncMock() // 42
195229

196230
## mockResolvedValueOnce
197231

198-
- **Type:** `(value: any) => MockInstance`
232+
```ts
233+
function mockResolvedValueOnce(value: Awaited<ReturnType<T>>): MockInstance<T>
234+
```
199235

200-
Accepts a value that will be resolved during the next function call. If chained, every consecutive call will resolve specified value.
236+
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.
201237

202238
```ts
203239
const asyncMock = vi
@@ -214,9 +250,11 @@ await asyncMock() // default
214250

215251
## mockReturnThis
216252

217-
- **Type:** `() => MockInstance`
253+
```ts
254+
function mockReturnThis(): MockInstance<T>
255+
```
218256

219-
Use this if you need to return `this` context from the method without invoking actual implementation. This is a shorthand for:
257+
Use this if you need to return the `this` context from the method without invoking the actual implementation. This is a shorthand for:
220258

221259
```ts
222260
spy.mockImplementation(function () {
@@ -226,9 +264,11 @@ spy.mockImplementation(function () {
226264

227265
## mockReturnValue
228266

229-
- **Type:** `(value: any) => MockInstance`
267+
```ts
268+
function mockReturnValue(value: ReturnType<T>): MockInstance<T>
269+
```
230270

231-
Accepts a value that will be returned whenever the mock function is called.
271+
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.
232272

233273
```ts
234274
const mock = vi.fn()
@@ -240,11 +280,13 @@ mock() // 43
240280

241281
## mockReturnValueOnce
242282

243-
- **Type:** `(value: any) => MockInstance`
283+
```ts
284+
function mockReturnValueOnce(value: ReturnType<T>): MockInstance<T>
285+
```
244286

245-
Accepts a value that will be returned during the next function call. If chained, every consecutive call will return the specified value.
287+
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.
246288

247-
When there are no more `mockReturnValueOnce` values to use, mock will fallback to previously defined implementation if there is one.
289+
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:
248290

249291
```ts
250292
const myMockFn = vi
@@ -259,6 +301,10 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn())
259301

260302
## mock.calls
261303

304+
```ts
305+
const calls: Parameters<T>[]
306+
```
307+
262308
This is an array containing all arguments for each call. One item of the array is the arguments of that call.
263309

264310
```js
@@ -275,10 +321,45 @@ fn.mock.calls === [
275321

276322
## mock.lastCall
277323

278-
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+
This contains the arguments of the last call. If mock wasn't called, it will return `undefined`.
279329

280330
## mock.results
281331

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+
282363
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:
283364

284365
- `'return'` - function returned without throwing.
@@ -314,6 +395,24 @@ fn.mock.results === [
314395

315396
## mock.settledResults
316397

398+
```ts
399+
interface MockSettledResultFulfilled<T> {
400+
type: 'fulfilled'
401+
value: T
402+
}
403+
404+
interface MockSettledResultRejected {
405+
type: 'rejected'
406+
value: any
407+
}
408+
409+
export type MockSettledResult<T> =
410+
| MockSettledResultFulfilled<T>
411+
| MockSettledResultRejected
412+
413+
const settledResults: MockSettledResult<Awaited<ReturnType<T>>>[]
414+
```
415+
317416
An array containing all values that were `resolved` or `rejected` from the function.
318417

319418
This array will be empty if the function was never resolved or rejected.
@@ -337,6 +436,10 @@ fn.mock.settledResults === [
337436

338437
## mock.invocationCallOrder
339438

439+
```ts
440+
const invocationCallOrder: number[]
441+
```
442+
340443
This property returns the order of the mock function's execution. It is an array of numbers that are shared between all defined mocks.
341444

342445
```js
@@ -353,6 +456,10 @@ fn2.mock.invocationCallOrder === [2]
353456

354457
## mock.contexts
355458

459+
```ts
460+
const contexts: ThisParameterType<T>[]
461+
```
462+
356463
This property is an array of `this` values used during each call to the mock function.
357464

358465
```js
@@ -368,6 +475,10 @@ fn.mock.contexts[1] === context
368475

369476
## mock.instances
370477

478+
```ts
479+
const instances: ReturnType<T>[]
480+
```
481+
371482
This property is an array containing all instances that were created when the mock was called with the `new` keyword. Note that this is an actual context (`this`) of the function, not a return value.
372483

373484
::: warning

0 commit comments

Comments
 (0)