Skip to content

Commit a0c1d37

Browse files
authored
fix!(spy): simplify mock function generic types and align with jest (#4784)
1 parent 7080513 commit a0c1d37

File tree

6 files changed

+159
-128
lines changed

6 files changed

+159
-128
lines changed

docs/guide/migration.md

+20-4
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,24 @@ This makes `.suite` optional; if the task is defined at the top level, it will n
7878

7979
This change also removes the file from `expect.getState().currentTestName` and makes `expect.getState().testPath` required.
8080

81+
### Simplified generic types of mock functions (e.g. `vi.fn<T>`, `Mock<T>`)
82+
83+
Previously `vi.fn<TArgs, TReturn>` accepted two generic types separately for arguemnts and return value. This is changed to directly accept a function type `vi.fn<T>` to simplify the usage.
84+
85+
```ts
86+
import { type Mock, vi } from 'vitest'
87+
88+
const add = (x: number, y: number): number => x + y
89+
90+
// using vi.fn<T>
91+
const mockAdd = vi.fn<Parameters<typeof add>, ReturnType<typeof add>>() // [!code --]
92+
const mockAdd = vi.fn<typeof add>() // [!code ++]
93+
94+
// using Mock<T>
95+
const mockAdd: Mock<Parameters<typeof add>, ReturnType<typeof add>> = vi.fn() // [!code --]
96+
const mockAdd: Mock<typeof add> = vi.fn() // [!code ++]
97+
```
98+
8199
## Migrating to Vitest 1.0
82100

83101
<!-- introduction -->
@@ -324,13 +342,11 @@ export default defineConfig({
324342
Vitest doesn't have an equivalent to `jest` namespace, so you will need to import types directly from `vitest`:
325343

326344
```ts
327-
let fn: jest.Mock<string, [string]> // [!code --]
345+
let fn: jest.Mock<(name: string) => number> // [!code --]
328346
import type { Mock } from 'vitest' // [!code ++]
329-
let fn: Mock<[string], string> // [!code ++]
347+
let fn: Mock<(name: string) => number> // [!code ++]
330348
```
331349

332-
Also, Vitest has `Args` type as a first argument instead of `Returns`, as you can see in diff.
333-
334350
### Timers
335351

336352
Vitest doesn't support Jest's legacy timers.

0 commit comments

Comments
 (0)