Skip to content

Commit

Permalink
docs: improve wording in mocking cheat sheet (#1617)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <[email protected]>
  • Loading branch information
sheremet-va and antfu authored Jul 9, 2022
1 parent 6358c8f commit 5b837f9
Showing 1 changed file with 25 additions and 9 deletions.
34 changes: 25 additions & 9 deletions docs/guide/mocking.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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()
Expand Down Expand Up @@ -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'
Expand All @@ -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()
```

Expand Down

0 comments on commit 5b837f9

Please sign in to comment.