import { composeMiddleware , Middleware } from '../src' ; import { compose } from './compose' ; describe ( 'composeMiddleware' , ( ) => { const expectedEvent = 'expected event' ; const expectedContext = 'expected context' ; const expectedResult = 'expected result' ; const mockHandler = jest . fn ( ) . mockResolvedValue ( expectedResult ) ; const mockMiddleware = jest . fn ( ) . mockReturnValue ( ( ) => new Promise ( ( ) => { } ) ) ; test ( 'returns a middleware function' , ( ) => { const output = composeMiddleware ( ) ; expect ( output ) . toBeInstanceOf ( Function ) ; } ) ; test ( 'returns identity on empty' , ( ) => { const emptyMiddlewares = composeMiddleware ( ) ; const result = emptyMiddlewares ( mockHandler ) ; expect ( result ) . toBe ( mockHandler ) ; } ) ; test ( 'returns middleware when unary' , ( ) => { const unaryMiddlewares = composeMiddleware ( mockMiddleware ) ; const expectedReturn = mockMiddleware ( mockHandler ) ; const actualReturn = unaryMiddlewares ( mockHandler ) ; expect ( actualReturn ) . toBe ( expectedReturn ) ; } ) ; test ( 'wraps middleware in order' , async ( ) => { const firstMiddleware = next => async ( event , context ) => { const result = await next ( event , context ) ; return 'first ' + result ; } ; const secondMiddleware = next => async ( event , context ) => { const result = await next ( event , context ) ; return 'second ' + result ; } ; const middlewares = composeMiddleware ( firstMiddleware , secondMiddleware ) ; const wrappedHandler = middlewares ( ( ) => new Promise ( resolve => { resolve ( 'expected' ) ; } ) ) ; const result = await wrappedHandler ( expectedEvent , expectedContext ) ; expect ( result ) . toBe ( 'first second expected' ) ; } ) ; } ) ; describe ( 'compose' , ( ) => { const expectedResult = 'expected result' ; const mockFn = jest . fn ( ) . mockReturnValue ( expectedResult ) ; test ( 'returns a function' , ( ) => { const output = compose ( ) ; expect ( output ) . toBeInstanceOf ( Function ) ; } ) ; test ( 'returns identity on empty' , ( ) => { const input = 'test' ; const emptyMiddlewares = compose ( ) ; const result = emptyMiddlewares ( input ) ; expect ( result ) . toBe ( input ) ; } ) ; test ( 'returns the same function when unary' , ( ) => { const input = 'test' ; const unaryFns = compose ( mockFn ) ; const expectedReturn = mockFn ( input ) ; const actualReturn = unaryFns ( input ) ; expect ( actualReturn ) . toBe ( expectedReturn ) ; } ) ; test ( 'wraps functions in correct order' , ( ) => { const input = 'test' ; const firstFn = ( input ) => `first ${ input }` ; const secondFn = ( input ) => `second ${ input }` ; const fns = compose ( firstFn , secondFn ) ; const expected = 'first second test' ; const actual = fns ( input ) ; expect ( actual ) . toEqual ( expected ) ; } ) ; } ) ;