import { UnmockPackage } from "unmock-core" ; export interface IRunnerOptions { maxLoop : number ; } const defaultRunnerOptions = { maxLoop : 20 , } ; const errorHandler = ( nTimes , errors , intermediaryErrors , cb ? ) => { const msg = ( rest ) => `This many tests failed: ${ errors . length + intermediaryErrors . length } out of ${ nTimes }. Here's the first error.\n${ rest }` ; if ( errors . length ) { errors [ 0 ] . message = msg ( errors [ 0 ] . message ) ; } else { intermediaryErrors [ 0 ] = typeof intermediaryErrors [ 0 ] === "string" ? msg ( intermediaryErrors [ 0 ] as string ) : { message : msg ( ( intermediaryErrors [ 0 ] as { message : string ; } ) . message ) , } ; } if ( cb ) { cb . fail ( intermediaryErrors . length ? intermediaryErrors [ 0 ] : errors [ 0 ] . message ) ; } else { throw errors [ 0 ] ; } } ; export interface IMeeshkanDoneCallback { success ( ... args ) : any ; fail ( error ? ) : any ; } export type MeeshkanProvidesCallback = ( cb : IMeeshkanDoneCallback ) => any ; export default ( assertionValidator ) => ( unmockPackage ) => ( fn ? , options ? ) => async ( cb ? ) => { const realOptions = { ... defaultRunnerOptions , ... options , } ; const intermediaryErrors = [ ] ; const intermediaryDoneCallback = { success : ( ) => { } , fail : ( ) => { } , } ; intermediaryDoneCallback . fail = ( error ) => { intermediaryErrors . push ( error ) ; } ; const errors = [ ] ; const res = [ ] ; for ( let i = 0 ; i < realOptions . maxLoop ; i ++ ) { unmockPackage . backend . faker . randomNumberGenerator . setSeed ( i ) ; unmockPackage . backend . faker . optionalsProbability = Math . random ( ) ; unmockPackage . backend . faker . minItems = Math . floor ( Math . random ( ) * 2 ** ( i % 5 ) ) ; try { const r = await ( fn ? fn ( intermediaryDoneCallback ) : undefined ) ; res . push ( r ) ; } catch ( e ) { if ( assertionValidator ( e ) ) { errors . push ( e ) ; } else { throw e ; } } finally { Object . entries ( unmockPackage . backend . serviceStore . services ) . forEach ( ( [ _ , service ] ) => { service . spy . resetHistory ( ) ; } ) ; } unmockPackage . backend . faker . optionalsProbability = 1.0 ; unmockPackage . backend . faker . minItems = 0 ; } if ( errors . length + intermediaryErrors . length > 0 ) { errorHandler ( realOptions . maxLoop , errors , intermediaryErrors , cb ) ; } else { cb && cb . success ( ) ; } } ;