From b2892977c2bb2de78cfb141747cd319b31cc95ef Mon Sep 17 00:00:00 2001 From: Michael Cousins Date: Wed, 10 Jan 2024 09:30:27 -0500 Subject: [PATCH] fix: defer Promise.reject to avoid unhandled rejection error (#8) Fixes #7 --- src/behaviors.ts | 3 ++- src/stubs.ts | 4 ++++ test/vitest-when.test.ts | 8 ++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/behaviors.ts b/src/behaviors.ts index fcb3cfa..cc15c8a 100644 --- a/src/behaviors.ts +++ b/src/behaviors.ts @@ -25,6 +25,7 @@ export interface BoundBehaviorStack { export interface BehaviorEntry { args: TArgs returnValue?: unknown + rejectError?: unknown throwError?: unknown doCallback?: AnyFunction | undefined times?: number | undefined @@ -86,7 +87,7 @@ export const createBehaviorStack = < ...getBehaviorOptions(values, options).map(({ value, times }) => ({ args, times, - returnValue: Promise.reject(value), + rejectError: value, })), ) }, diff --git a/src/stubs.ts b/src/stubs.ts index 6a2c8b0..dd30995 100644 --- a/src/stubs.ts +++ b/src/stubs.ts @@ -32,6 +32,10 @@ export const configureStub = ( throw behavior.throwError as Error } + if (behavior?.rejectError) { + return Promise.reject(behavior.rejectError) + } + if (behavior?.doCallback) { return behavior.doCallback(...args) } diff --git a/test/vitest-when.test.ts b/test/vitest-when.test.ts index 78d708e..4f3ae86 100644 --- a/test/vitest-when.test.ts +++ b/test/vitest-when.test.ts @@ -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) + }) })