Skip to content

Commit b289297

Browse files
authored
fix: defer Promise.reject to avoid unhandled rejection error (#8)
Fixes #7
1 parent f83b7a0 commit b289297

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

src/behaviors.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export interface BoundBehaviorStack<TReturn> {
2525
export interface BehaviorEntry<TArgs extends unknown[]> {
2626
args: TArgs
2727
returnValue?: unknown
28+
rejectError?: unknown
2829
throwError?: unknown
2930
doCallback?: AnyFunction | undefined
3031
times?: number | undefined
@@ -86,7 +87,7 @@ export const createBehaviorStack = <
8687
...getBehaviorOptions(values, options).map(({ value, times }) => ({
8788
args,
8889
times,
89-
returnValue: Promise.reject(value),
90+
rejectError: value,
9091
})),
9192
)
9293
},

src/stubs.ts

+4
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ export const configureStub = <TFunc extends AnyFunction>(
3232
throw behavior.throwError as Error
3333
}
3434

35+
if (behavior?.rejectError) {
36+
return Promise.reject(behavior.rejectError)
37+
}
38+
3539
if (behavior?.doCallback) {
3640
return behavior.doCallback(...args)
3741
}

test/vitest-when.test.ts

+8
Original file line numberDiff line numberDiff line change
@@ -256,4 +256,12 @@ describe('vitest-when', () => {
256256

257257
expect(spy({ foo: { bar: { baz: 0 } } })).toEqual(100)
258258
})
259+
260+
it('should not trigger unhandled rejection warnings when rejection unused', () => {
261+
const spy = vi.fn()
262+
const error = new Error('uh uhh')
263+
subject.when(spy).calledWith('/api/foo').thenReject(error)
264+
// intentionally do not call the spy
265+
expect(true).toBe(true)
266+
})
259267
})

0 commit comments

Comments
 (0)