diff --git a/docs/guide/mocking.md b/docs/guide/mocking.md index 1c74d619ceb0..e05615c845b8 100644 --- a/docs/guide/mocking.md +++ b/docs/guide/mocking.md @@ -379,23 +379,25 @@ const instance = new SomeClass() vi.spyOn(instance, 'method') ``` -- Spy on module export function +- Mock exported variables ```ts -import * as exports from 'some-path' -vi.spyOn(exports, 'function') +// some-path.ts +export const getter = 'variable' ``` - -- Spy on module export setter/getter ```ts +// some-path.test.ts import * as exports from 'some-path' -vi.spyOn(exports, 'getter', 'get') -vi.spyOn(exports, 'setter', 'set') +vi.spyOn(exports, 'getter', 'get').mockReturnValue('mocked') ``` -- Mock a module export function +- Mock exported function Example with `vi.mock`: ```ts +// some-path.ts +export function method() {} +``` +```ts import { method } from 'some-path' vi.mock('some-path', () => ({ method: vi.fn() @@ -408,10 +410,14 @@ import * as exports from 'some-path' vi.spyOn(exports, 'method').mockImplementation(() => {}) ``` -- Mock a module export class implementation +- Mock exported class implementation Example with `vi.mock` and prototype: ```ts +// some-path.ts +export class SomeClass {} +``` +```ts import { SomeClass } from 'some-path' vi.mock('some-path', () => { const SomeClass = vi.fn() @@ -446,6 +452,13 @@ vi.spyOn(exports, 'SomeClass').mockImplementation(() => { Example using cache: +```ts +// some-path.ts +export function useObject() { + return { method: () => true } +} +``` + ```ts // useObject.js import { useObject } from 'some-path' @@ -464,12 +477,15 @@ vi.mock('some-path', () => { method: vi.fn(), } } + // now everytime useObject() is called it will + // return the same object reference return _cache } return { useObject } }) const obj = useObject() +// obj.method was called inside some-path expect(obj.method).toHaveBeenCalled() ```