Skip to content

Commit

Permalink
Merge branch 'main' into fix-eco-ci-6
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa committed Nov 13, 2024
2 parents 2655bd5 + 76169a1 commit f5fbd55
Show file tree
Hide file tree
Showing 11 changed files with 476 additions and 308 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ jobs:

- name: Get changed files
id: changed-files
uses: tj-actions/changed-files@c3a1bb2c992d77180ae65be6ae6c166cf40f857c # v45.0.3
uses: tj-actions/changed-files@4edd678ac3f81e2dc578756871e4d00c19191daf # v45.0.4
with:
files: |
docs/**
Expand Down
203 changes: 157 additions & 46 deletions docs/api/mock.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,41 +20,55 @@ getApplesSpy.mock.calls.length === 1

You should use mock assertions (e.g., [`toHaveBeenCalled`](/api/expect#tohavebeencalled)) on [`expect`](/api/expect) to assert mock result. This API reference describes available properties and methods to manipulate mock behavior.

::: tip
The custom function implementation in the types below is marked with a generic `<T>`.
:::

## getMockImplementation

- **Type:** `(...args: any) => any`
```ts
function getMockImplementation(): T | undefined
```

Returns current mock implementation if there is one.

If mock was created with [`vi.fn`](/api/vi#vi-fn), it will consider passed down method as a mock implementation.
If the mock was created with [`vi.fn`](/api/vi#vi-fn), it will use the provided method as the mock implementation.

If mock was created with [`vi.spyOn`](/api/vi#vi-spyon), it will return `undefined` unless a custom implementation was provided.
If the mock was created with [`vi.spyOn`](/api/vi#vi-spyon), it will return `undefined` unless a custom implementation is provided.

## getMockName

- **Type:** `() => string`
```ts
function getMockName(): string
```

Use it to return the name given to mock with method `.mockName(name)`.
Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, it will return `vi.fn()`.

## mockClear

- **Type:** `() => MockInstance`
```ts
function mockClear(): MockInstance<T>
```

Clears all information about every call. After calling it, all properties on `.mock` will return empty state. This method does not reset implementations. It is useful if you need to clean up mock between different assertions.
Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions.

If you want this method to be called before each test automatically, you can enable [`clearMocks`](/config/#clearmocks) setting in config.
To automatically call this method before each test, enable the [`clearMocks`](/config/#clearmocks) setting in the configuration.

## mockName

- **Type:** `(name: string) => MockInstance`
```ts
function mockName(name: string): MockInstance<T>
```

Sets internal mock name. Useful to see the name of the mock if assertion fails.
Sets the internal mock name. This is useful for identifying the mock when an assertion fails.

## mockImplementation

- **Type:** `(fn: Function) => MockInstance`
```ts
function mockImplementation(fn: T): MockInstance<T>
```

Accepts a function that will be used as an implementation of the mock.
Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function.

```ts
const mockFn = vi.fn().mockImplementation((apples: number) => apples + 1)
Expand All @@ -72,21 +86,23 @@ mockFn.mock.calls[1][0] === 1 // true

## mockImplementationOnce

- **Type:** `(fn: Function) => MockInstance`
```ts
function mockImplementationOnce(fn: T): MockInstance<T>
```

Accepts a function that will be used as mock's implementation during the next call. Can be chained so that multiple function calls produce different results.
Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. This method can be chained to produce different results for multiple function calls.

```ts
const myMockFn = vi
.fn()
.mockImplementationOnce(() => true)
.mockImplementationOnce(() => false)
.mockImplementationOnce(() => true) // 1st call
.mockImplementationOnce(() => false) // 2nd call
myMockFn() // true
myMockFn() // false
myMockFn() // 1st call: true
myMockFn() // 2nd call: false
```

When the mocked function runs out of implementations, it will invoke the default implementation that was set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called:
When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called:

```ts
const myMockFn = vi
Expand All @@ -100,8 +116,16 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn())

## withImplementation

- **Type:** `(fn: Function, callback: () => void) => MockInstance`
- **Type:** `(fn: Function, callback: () => Promise<unknown>) => Promise<MockInstance>`
```ts
function withImplementation(
fn: T,
cb: () => void
): MockInstance<T>
function withImplementation(
fn: T,
cb: () => Promise<void>
): Promise<MockInstance<T>>
```

Overrides the original mock implementation temporarily while the callback is being executed.

Expand Down Expand Up @@ -137,55 +161,65 @@ Note that this method takes precedence over the [`mockImplementationOnce`](#mock

## mockRejectedValue

- **Type:** `(value: any) => MockInstance`
```ts
function mockRejectedValue(value: unknown): MockInstance<T>
```

Accepts an error that will be rejected when async function is called.

```ts
const asyncMock = vi.fn().mockRejectedValue(new Error('Async error'))
await asyncMock() // throws "Async error"
await asyncMock() // throws Error<'Async error'>
```

## mockRejectedValueOnce

- **Type:** `(value: any) => MockInstance`
```ts
function mockRejectedValueOnce(value: unknown): MockInstance<T>
```

Accepts a value that will be rejected during the next function call. If chained, every consecutive call will reject specified value.
Accepts a value that will be rejected during the next function call. If chained, each consecutive call will reject the specified value.

```ts
const asyncMock = vi
.fn()
.mockResolvedValueOnce('first call')
.mockRejectedValueOnce(new Error('Async error'))
await asyncMock() // first call
await asyncMock() // throws "Async error"
await asyncMock() // 'first call'
await asyncMock() // throws Error<'Async error'>
```

## mockReset

- **Type:** `() => MockInstance`
```ts
function mockReset(): MockInstance<T>
```

Does what `mockClear` does and makes inner implementation an empty function (returning `undefined` when invoked). This also resets all "once" implementations. This is useful when you want to completely reset a mock to the default state.
Performs the same actions as `mockClear` and sets the inner implementation to an empty function (returning `undefined` when invoked). This also resets all "once" implementations. It is useful for completely resetting a mock to its default state.

If you want this method to be called before each test automatically, you can enable [`mockReset`](/config/#mockreset) setting in config.
To automatically call this method before each test, enable the [`mockReset`](/config/#mockreset) setting in the configuration.

## mockRestore

- **Type:** `() => MockInstance`
```ts
function mockRestore(): MockInstance<T>
```

Does what `mockReset` does and restores inner implementation to the original function.
Performs the same actions as `mockReset` and restores the inner implementation to the original function.

Note that restoring mock from `vi.fn()` will set implementation to an empty function that returns `undefined`. Restoring a `vi.fn(impl)` will restore implementation to `impl`.
Note that restoring a mock created with `vi.fn()` will set the implementation to an empty function that returns `undefined`. Restoring a mock created with `vi.fn(impl)` will restore the implementation to `impl`.

If you want this method to be called before each test automatically, you can enable [`restoreMocks`](/config/#restoremocks) setting in config.
To automatically call this method before each test, enable the [`restoreMocks`](/config/#restoremocks) setting in the configuration.

## mockResolvedValue

- **Type:** `(value: any) => MockInstance`
```ts
function mockResolvedValue(value: Awaited<ReturnType<T>>): MockInstance<T>
```

Accepts a value that will be resolved when async function is called.
Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function.

```ts
const asyncMock = vi.fn().mockResolvedValue(42)
Expand All @@ -195,9 +229,11 @@ await asyncMock() // 42

## mockResolvedValueOnce

- **Type:** `(value: any) => MockInstance`
```ts
function mockResolvedValueOnce(value: Awaited<ReturnType<T>>): MockInstance<T>
```

Accepts a value that will be resolved during the next function call. If chained, every consecutive call will resolve specified value.
Accepts a value that will be resolved during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value.

```ts
const asyncMock = vi
Expand All @@ -214,9 +250,11 @@ await asyncMock() // default

## mockReturnThis

- **Type:** `() => MockInstance`
```ts
function mockReturnThis(): MockInstance<T>
```

Use this if you need to return `this` context from the method without invoking actual implementation. This is a shorthand for:
Use this if you need to return the `this` context from the method without invoking the actual implementation. This is a shorthand for:

```ts
spy.mockImplementation(function () {
Expand All @@ -226,9 +264,11 @@ spy.mockImplementation(function () {

## mockReturnValue

- **Type:** `(value: any) => MockInstance`
```ts
function mockReturnValue(value: ReturnType<T>): MockInstance<T>
```

Accepts a value that will be returned whenever the mock function is called.
Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.

```ts
const mock = vi.fn()
Expand All @@ -240,11 +280,13 @@ mock() // 43

## mockReturnValueOnce

- **Type:** `(value: any) => MockInstance`
```ts
function mockReturnValueOnce(value: ReturnType<T>): MockInstance<T>
```

Accepts a value that will be returned during the next function call. If chained, every consecutive call will return the specified value.
Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.

When there are no more `mockReturnValueOnce` values to use, mock will fallback to previously defined implementation if there is one.
When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called:

```ts
const myMockFn = vi
Expand All @@ -259,6 +301,10 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn())

## mock.calls

```ts
const calls: Parameters<T>[]
```

This is an array containing all arguments for each call. One item of the array is the arguments of that call.

```js
Expand All @@ -275,10 +321,45 @@ fn.mock.calls === [

## mock.lastCall

This contains the arguments of the last call. If mock wasn't called, will return `undefined`.
```ts
const lastCall: Parameters<T> | undefined
```

This contains the arguments of the last call. If mock wasn't called, it will return `undefined`.

## mock.results

```ts
interface MockResultReturn<T> {
type: 'return'
/**
* The value that was returned from the function.
* If function returned a Promise, then this will be a resolved value.
*/
value: T
}
interface MockResultIncomplete {
type: 'incomplete'
value: undefined
}
interface MockResultThrow {
type: 'throw'
/**
* An error that was thrown during function execution.
*/
value: any
}
type MockResult<T> =
| MockResultReturn<T>
| MockResultThrow
| MockResultIncomplete
const results: MockResult<ReturnType<T>>[]
```

This is an array containing all values that were `returned` from the function. One item of the array is an object with properties `type` and `value`. Available types are:

- `'return'` - function returned without throwing.
Expand Down Expand Up @@ -314,6 +395,24 @@ fn.mock.results === [

## mock.settledResults

```ts
interface MockSettledResultFulfilled<T> {
type: 'fulfilled'
value: T
}
interface MockSettledResultRejected {
type: 'rejected'
value: any
}
export type MockSettledResult<T> =
| MockSettledResultFulfilled<T>
| MockSettledResultRejected
const settledResults: MockSettledResult<Awaited<ReturnType<T>>>[]
```

An array containing all values that were `resolved` or `rejected` from the function.

This array will be empty if the function was never resolved or rejected.
Expand All @@ -337,6 +436,10 @@ fn.mock.settledResults === [

## mock.invocationCallOrder

```ts
const invocationCallOrder: number[]
```

This property returns the order of the mock function's execution. It is an array of numbers that are shared between all defined mocks.

```js
Expand All @@ -353,6 +456,10 @@ fn2.mock.invocationCallOrder === [2]

## mock.contexts

```ts
const contexts: ThisParameterType<T>[]
```

This property is an array of `this` values used during each call to the mock function.

```js
Expand All @@ -368,6 +475,10 @@ fn.mock.contexts[1] === context

## mock.instances

```ts
const instances: ReturnType<T>[]
```

This property is an array containing all instances that were created when the mock was called with the `new` keyword. Note that this is an actual context (`this`) of the function, not a return value.

::: warning
Expand Down
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"@unocss/reset": "^0.64.0",
"@vite-pwa/assets-generator": "^0.2.6",
"@vite-pwa/vitepress": "^0.5.3",
"@vitejs/plugin-vue": "^5.1.4",
"@vitejs/plugin-vue": "^5.1.5",
"https-localhost": "^4.7.1",
"tinyglobby": "^0.2.10",
"unocss": "^0.64.0",
Expand Down
Loading

0 comments on commit f5fbd55

Please sign in to comment.