samedi 24 février 2018

Is It Possible To Extend A Jest / Expect Matcher

I would like to extend Jest's isEqual matcher so that the expected value is transformed before comparison (this allows me to use multiline strings in tests). All I need to do is run the expected value through a the indentToFirstLine function from the lib: indent-to-first-line before passing it to isEqual. Obviously I don't want to have to do this everywhere I need it, so it makes sense to fold this into a matcher, and as I want identical functionality to Jest / Expect's isEqual matcher, it makes sense to utilise that.

I've tried the following:

import indentToFirstLine from 'indent-to-first-line'
import expect from 'expect'

const toEqualMultiline = (received, expectedTemplateString) => {
  const expected = indentToFirstLine(expectedTemplateString)
  return expect(received).toEqual(expected)
}

export default toEqualMultiline

However expect(received).toEqual(expected) doesn't return a value, so the value returned from my matcher in undefined, causing Jest to error:

Unexpected return from a matcher function. Matcher functions should return an object in the following format: {message?: string | function, pass: boolean} 'undefined' was returned

Is it possible for me to use toEqual from within my own matcher?

Aucun commentaire:

Enregistrer un commentaire