Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/tests / src / jest / extendJest.ts
Size: Mime:
// or diff..
import chalk from 'chalk'
import {
  ExoticJestExpecterMap,
  ExoticJestExpect,
  Predicate,
  PassFailArgs,
  MsgFunction,
  Msg,
} from '../declarations/jest.extended'
import { stringify } from './deps.stringify'
import { invariant } from './deps.invariant'

const defaultPassMsg: MsgFunction = (args: PassFailArgs) => {
  const received = stringify(args.received)
  const actual = stringify(args.actual)
  return `${chalk.underline(args.key)} ${chalk.green('pass')}; \n${chalk.bold(
    'received'
  )}: \n ${chalk.dim(received)}; \n${chalk.bold('expected')}: ${chalk.dim(
    actual
  )}; \n\n`
}
const defaultFailMsg: MsgFunction = (args: PassFailArgs) => {
  const received = stringify(args.received)
  const actual = stringify(args.actual)
  return `${chalk.underline(args.key)} ${chalk.red('fail')}; \n${chalk.bold(
    'received'
  )}: \n ${chalk.magentaBright(received)}; \n${chalk.bold(
    'expected'
  )}: \n ${chalk.bgRedBright(actual)}; \n\n`
}

const toJestExtend = (
  predicate: Predicate,
  key: string,
  passMsg: Msg = defaultPassMsg,
  failMsg: MsgFunction = defaultFailMsg
) => {
  return function(
    this: jest.MatcherUtils,
    received: any,
    actual: any = chalk.underline(key),
    ...remainingActuals: any[]
  ) {
    const passFn = passMsg as MsgFunction
    const failFn = failMsg as MsgFunction

    invariant(
      typeof predicate === 'function',
      'predicate must be a function for: ' + key
    )
    invariant(
      typeof passFn === 'function',
      'passFn must be a function for: ' + key
    )
    invariant(
      typeof failFn === 'function',
      'failFn must be a function for: ' + key
    )

    const pass = predicate(received, actual)

    if (pass) {
      return {
        message: () => passFn({ received, actual, key }),
        pass: true,
      }
    } else {
      return {
        message: () => failFn({ received, actual, key }),
        pass: false,
      }
    }
  }
}

function fromObjToJestExpect(obj: ExoticJestExpecterMap): ExoticJestExpect {
  const asExpected = {}
  Object.keys(obj).forEach(key => {
    asExpected[key] = toJestExtend(obj[key], key)
  })
  return asExpected as ExoticJestExpect
}
function extend(obj: ExoticJestExpecterMap) {
  const expectedObjMap = fromObjToJestExpect(obj)
  expect.extend(expectedObjMap as jest.ExpectExtendMap)
}

export { defaultPassMsg, defaultFailMsg, toJestExtend, extend }