Skip to content

Commit

Permalink
docs: add vi.mocked(..., { partial: true }) example (#6783)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa authored Oct 31, 2024
1 parent 270f99c commit 234674d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
26 changes: 22 additions & 4 deletions docs/api/vi.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,13 +217,31 @@ Type helper for TypeScript. Just returns the object that was passed.
When `partial` is `true` it will expect a `Partial<T>` as a return value. By default, this will only make TypeScript believe that the first level values are mocked. You can pass down `{ deep: true }` as a second argument to tell TypeScript that the whole object is mocked, if it actually is.

```ts
import example from './example.js'
// example.ts
export function add(x: number, y: number): number {
return x + y
}

export function fetchSomething(): Promise<Response> {
return fetch('https://vitest.dev/')
}
```

vi.mock('./example.js')
```ts
// example.test.ts
import * as example from './example'

vi.mock('./example')

test('1 + 1 equals 10', async () => {
vi.mocked(example.calc).mockReturnValue(10)
expect(example.calc(1, '+', 1)).toBe(10)
vi.mocked(example.add).mockReturnValue(10)
expect(example.add(1, 1)).toBe(10)
})

test('mock return value with only partially correct typing', async () => {
vi.mocked(example.fetchSomething).mockResolvedValue(new Response('hello'))
vi.mocked(example.fetchSomething, { partial: true }).mockResolvedValue({ ok: false })
// vi.mocked(example.someFn).mockResolvedValue({ ok: false }) // this is a type error
})
```

Expand Down
9 changes: 9 additions & 0 deletions test/core/test/vi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,15 @@ describe('testing vi utils', () => {
vi.mocked(mockFactoryAsync, { partial: true, deep: true }).mockResolvedValue({
baz: 'baz',
})

function fetchSomething(): Promise<Response> {
return fetch('https://vitest.dev/')
};
if (0) {
// type check only
vi.mocked(fetchSomething).mockResolvedValue(new Response(null))
vi.mocked(fetchSomething, { partial: true }).mockResolvedValue({ ok: false })
}
})

test('vi.fn and Mock type', () => {
Expand Down

0 comments on commit 234674d

Please sign in to comment.