Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: defer Promise.reject to avoid unhandled rejection error #8

Merged
merged 1 commit into from
Jan 10, 2024
Merged
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
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)
})
})