Skip to content

Commit c10a129

Browse files
authored
fix: accept awaited value in vi.when thenResolve (#11084)
1 parent 488c046 commit c10a129

2 files changed

Lines changed: 23 additions & 2 deletions

File tree

‎packages/vitest/src/integrations/mock/when.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ type CalledWithInstance<ReturnType, Fn extends Procedure> = When<Fn> & {
8585
* @param options - Optional behavior configuration.
8686
* @returns The same {@linkcode when|vi.when} instance for chaining.
8787
*/
88-
thenResolve: (value: ReturnType, options?: BehaviorOptions | undefined) => CalledWithInstance<ReturnType, Fn>
88+
thenResolve: (value: Awaited<ReturnType>, options?: BehaviorOptions | undefined) => CalledWithInstance<ReturnType, Fn>
8989

9090
/**
9191
* Schedules a synchronous return value for a single call with the registered arguments, then removes the behavior.
@@ -103,7 +103,7 @@ type CalledWithInstance<ReturnType, Fn extends Procedure> = When<Fn> & {
103103
* @param options - Optional behavior configuration.
104104
* @returns The same {@linkcode when|vi.when} instance for chaining.
105105
*/
106-
thenResolveOnce: (value: ReturnType, options?: OnceBehaviorOptions | undefined) => CalledWithInstance<ReturnType, Fn>
106+
thenResolveOnce: (value: Awaited<ReturnType>, options?: OnceBehaviorOptions | undefined) => CalledWithInstance<ReturnType, Fn>
107107

108108
/**
109109
* Schedules a thrown error for when the spy is called with the registered arguments.

‎test/unit/test/mocking/vi-when.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,27 @@ describe('vi.when()', () => {
136136
expect(w).toHaveBeenExhausted()
137137
})
138138

139+
test('resolves with an unwrapped value for an async function', async () => {
140+
const spy = vi.fn<(...args: FnData['args']) => Promise<FnData['value']>>()
141+
142+
const args: FnData['args'] = ['a', 0]
143+
const value: FnData['value'] = 97
144+
145+
const w = vi.when(spy)
146+
.calledWith(...args)
147+
.thenResolve(value)
148+
.thenResolveOnce(value)
149+
150+
expect(w).not.toHaveBeenExhausted()
151+
152+
await expect(spy(...args)).resolves.toBe(value)
153+
await expect(spy(...args)).resolves.toBe(value)
154+
155+
expect(spy).toHaveBeenCalledTimes(2)
156+
157+
expect(w).toHaveBeenExhausted()
158+
})
159+
139160
test('rejects a promise when using `toReject`', async () => {
140161
const spy = vi.fn<Fn>()
141162

0 commit comments

Comments
 (0)