import { ReturnValue } from '../expectation/expectation' ; import { createInvocationCount , InvocationCount } from './invocation-count' ; import { PendingExpectation } from '../when/pending-expectation' ; type PromiseStub < R , P > = { param value example example thenReturn ( value ) : InvocationCount ; param promiseValue thenResolve ( promiseValue ) : InvocationCount ; param error thenReject ( error ) : InvocationCount ; param message thenReject ( message ) : InvocationCount ; /**
     * Make the current call reject with `new Error()`.
     */ thenReject ( ) : InvocationCount ; } ; type NonPromiseStub < R > = { param returnValue thenReturn ( returnValue ) : InvocationCount ; param error thenThrow ( error ) : InvocationCount ; param message thenThrow ( message ) : InvocationCount ; /**
     * Make the current call throw `new Error()`.
     */ thenThrow ( ) : InvocationCount ; } ; export type Stub < T > = [ T ] extends [ Promise < infer U > ] ? PromiseStub < U , T > : NonPromiseStub < T > ; /**
 * Set a return value for the currently pending expectation.
 */ const finishPendingExpectation = ( returnValue , pendingExpectation ) => { const finishedExpectation = pendingExpectation . finish ( returnValue ) ; pendingExpectation . clear ( ) ; return createInvocationCount ( finishedExpectation ) ; } ; const getError = ( errorOrMessage ) : Error => { if ( typeof errorOrMessage === 'string' ) { return new Error ( errorOrMessage ) ; } if ( errorOrMessage instanceof Error ) { return errorOrMessage ; } return new Error ( ) ; } ; export const createReturns = < R > ( pendingExpectation ) : Stub < R > => { const nonPromiseStub = { thenReturn : ( returnValue ) : InvocationCount => finishPendingExpectation ( { value : returnValue , isError : false , isPromise : false } , pendingExpectation ) , thenThrow : ( errorOrMessage ? ) : InvocationCount => finishPendingExpectation ( { value : getError ( errorOrMessage ) , isError : true , isPromise : false } , pendingExpectation ) , } ; const promiseStub = { thenReturn : ( promise ) : InvocationCount => finishPendingExpectation ( { value : promise , isError : false , isPromise : false , } , pendingExpectation ) , thenResolve : ( promiseValue ) : InvocationCount => finishPendingExpectation ( { value : promiseValue , isError : false , isPromise : true , } , pendingExpectation ) , thenReject : ( errorOrMessage ? ) : InvocationCount => finishPendingExpectation ( { value : getError ( errorOrMessage ) , isError : true , isPromise : true , } , pendingExpectation ) , } ; return { ... nonPromiseStub , ... promiseStub } ; } ;