Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,11 @@ test('stubbing with vitest-when', () => {

You should call `vi.resetAllMocks()` in your suite's `afterEach` hook to remove the implementation added by `when`. You can also set Vitest's [`mockReset`](https://vitest.dev/config/#mockreset) config to `true` instead of using `afterEach`.

> [!NOTE]
> In Vitest 3 and earlier, `mockReset` will clear any default implementation passed to `vi.fn()` (e.g. `vi.fn(() => 'fallback')`). To preserve default implementations, **upgrade to Vitest 4 or later**. See [fallback implementations][] for more details and a workaround for earlier versions of Vitest.

[vitest's mock functions]: https://vitest.dev/api/mock.html
[fallback implementations]: #fallback
[stubs]: https://en.wikipedia.org/wiki/Test_stub
[when]: #whenmock-tfunc-options-whenoptions-stubwrappertfunc
[called-with]: #calledwithargs-parameterstfunc-stubtfunc
Expand Down Expand Up @@ -210,6 +214,12 @@ import type { WhenOptions } from 'vitest-when'
| `ignoreExtraArgs` | `false` | boolean | Ignore extra arguments when matching arguments |
| `times` | N/A | integer | Only trigger configured behavior a number of times |

#### `vi.spyOn()`

`when()` works with `vi.spyOn()` mocks, but unmatched calls will no-op and return `undefined` rather than falling back to the real implementation. If you need the real implementation as a fallback, consider wrapping the module in an adapter and using `vi.fn()` instead — see [Don't mock what you don't own][no-mock-own].

[no-mock-own]: https://github.com/testdouble/contributing-tests/wiki/Don't-mock-what-you-don't-own

### `.calledWith(...args: Parameters<TFunc>): Stub<TFunc>`

Create a stub that matches a given set of arguments which you can configure with different behaviors using methods like [`.thenReturn(...)`][then-return].
Expand Down Expand Up @@ -274,6 +284,19 @@ mock('hello') // "world"
mock('jello') // "you messed up!"
```

> [!NOTE]
> In Vitest 3 and earlier, `mockReset` will clear any default implementation passed to `vi.fn()`. To preserve default implementations, **upgrade to Vitest 4 or later**.
>
> As a workaround in Vitest 3 and earlier, you can use a `beforeEach` instead:
>
> ```diff
> - const mockWithFallback = vi.fn(() => 'fallback')
> + const mockWithFallback = vi.fn()
> + beforeEach(() => {
> + mockWithFallback.mockImplementation(() => 'fallback')
> + })
> ```

[mock API]: https://vitest.dev/api/mock.html

### `.thenReturn(value: TReturn) -> Mock<TFunc>`
Expand Down
46 changes: 0 additions & 46 deletions src/fallback-implementation.ts

This file was deleted.

6 changes: 4 additions & 2 deletions src/stubs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import {
createBehaviorStack,
} from './behaviors.ts'
import { NotAMockFunctionError } from './errors.ts'
import { getFallbackImplementation } from './fallback-implementation.ts'
import type {
AnyFunction,
AnyMockable,
AsFunction,
Mock,
Expand All @@ -30,7 +30,9 @@ export const configureMock = <TFunc extends AnyMockable>(
}

const behaviorStack = createBehaviorStack<TFunc>()
const fallbackImplementation = getFallbackImplementation(mock)
const fallbackImplementation = mock.getMockImplementation() as
| AnyFunction
| undefined

function implementation(this: ThisType<TFunc>, ...args: ParametersOf<TFunc>) {
const behavior = behaviorStack.use(args)?.behavior ?? {
Expand Down
15 changes: 0 additions & 15 deletions test/vitest-when.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { describe, expect, it, vi } from 'vitest'
import vitestPkg from 'vitest/package.json' with { type: 'json' }

import * as subject from '../src/vitest-when.ts'
import { SimpleClass } from './fixtures.ts'
Expand All @@ -20,7 +19,6 @@ expect.extend({
})

const noop = () => undefined
const vitestMajorVersion = Number(vitestPkg.version.split('.')[0])

describe('vitest-when', () => {
it('should raise an error if passed a non-spy', () => {
Expand Down Expand Up @@ -62,19 +60,6 @@ describe('vitest-when', () => {
expect(spy()).toEqual(100)
})

it.skipIf(vitestMajorVersion < 3)(
'should fall back to original implementation after reset',
() => {
const spy = vi.fn((n) => 2 * n)

vi.resetAllMocks()

subject.when(spy).calledWith(1).thenReturn(4)
expect(spy(1)).toEqual(4)
expect(spy(2)).toEqual(4)
},
)

it('should return a number of times', () => {
const spy = subject
.when(vi.fn(), { times: 2 })
Expand Down