[READ-ONLY] Mirror of https://github.com/vitest-dev/vitest. Next generation testing framework powered by Vite. vitest.dev
test testing-tools vite
12

Configure Feed

Select the types of activity you want to include in your feed.

docs: add `vi.mocked(..., { partial: true })` example (#6783)

authored by

Hiroshi Ogawa and committed by
GitHub
(Oct 31, 2024, 4:40 PM +0100) 234674da 270f99c1

+31 -4
+22 -4
docs/api/vi.md
··· 217 217 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. 218 218 219 219 ```ts 220 - import example from './example.js' 220 + // example.ts 221 + export function add(x: number, y: number): number { 222 + return x + y 223 + } 221 224 222 - vi.mock('./example.js') 225 + export function fetchSomething(): Promise<Response> { 226 + return fetch('https://vitest.dev/') 227 + } 228 + ``` 229 + 230 + ```ts 231 + // example.test.ts 232 + import * as example from './example' 233 + 234 + vi.mock('./example') 223 235 224 236 test('1 + 1 equals 10', async () => { 225 - vi.mocked(example.calc).mockReturnValue(10) 226 - expect(example.calc(1, '+', 1)).toBe(10) 237 + vi.mocked(example.add).mockReturnValue(10) 238 + expect(example.add(1, 1)).toBe(10) 239 + }) 240 + 241 + test('mock return value with only partially correct typing', async () => { 242 + vi.mocked(example.fetchSomething).mockResolvedValue(new Response('hello')) 243 + vi.mocked(example.fetchSomething, { partial: true }).mockResolvedValue({ ok: false }) 244 + // vi.mocked(example.someFn).mockResolvedValue({ ok: false }) // this is a type error 227 245 }) 228 246 ``` 229 247
+9
test/core/test/vi.spec.ts
··· 83 83 vi.mocked(mockFactoryAsync, { partial: true, deep: true }).mockResolvedValue({ 84 84 baz: 'baz', 85 85 }) 86 + 87 + function fetchSomething(): Promise<Response> { 88 + return fetch('https://vitest.dev/') 89 + }; 90 + if (0) { 91 + // type check only 92 + vi.mocked(fetchSomething).mockResolvedValue(new Response(null)) 93 + vi.mocked(fetchSomething, { partial: true }).mockResolvedValue({ ok: false }) 94 + } 86 95 }) 87 96 88 97 test('vi.fn and Mock type', () => {