Skip to content

Commit

Permalink
fix: defer Promise.reject to avoid unhandled rejection error
Browse files Browse the repository at this point in the history
Fixes #7
  • Loading branch information
mcous committed Jan 10, 2024
1 parent f83b7a0 commit 44a869b
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/behaviors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export interface BoundBehaviorStack<TReturn> {
export interface BehaviorEntry<TArgs extends unknown[]> {
args: TArgs
returnValue?: unknown
rejectError?: unknown
throwError?: unknown
doCallback?: AnyFunction | undefined
times?: number | undefined
Expand Down Expand Up @@ -86,7 +87,7 @@ export const createBehaviorStack = <
...getBehaviorOptions(values, options).map(({ value, times }) => ({
args,
times,
returnValue: Promise.reject(value),
rejectError: value,
})),
)
},
Expand Down
4 changes: 4 additions & 0 deletions src/stubs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ export const configureStub = <TFunc extends AnyFunction>(
throw behavior.throwError as Error
}

if (behavior?.rejectError) {
return Promise.reject(behavior.rejectError)
}

if (behavior?.doCallback) {
return behavior.doCallback(...args)
}
Expand Down
8 changes: 8 additions & 0 deletions test/vitest-when.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,4 +256,12 @@ describe('vitest-when', () => {

expect(spy({ foo: { bar: { baz: 0 } } })).toEqual(100)
})

it('should not trigger unhandled rejection warnings when rejection unused', () => {
const spy = vi.fn()
const error = new Error('uh uhh')
subject.when(spy).calledWith('/api/foo').thenReject(error)
// intentionally do not call the spy
expect(true).toBe(true)
})
})

0 comments on commit 44a869b

Please sign in to comment.