Created
August 8, 2020 11:39
-
-
Save phartenfeller/f099773b29c6dfce15f650b874600837 to your computer and use it in GitHub Desktop.
Jest custom matcher that ignores whitespace and new lines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To use: | |
// Put `<rootDir>/path/to/toMatchIgnoreWhitespace.js` in your Jest config under setupFiles | |
// Call it in your tests like this: | |
// expect(received).toMatchIgnoreWhitespace(expected); | |
// Modified version of: https://gist.github.com/cassidoo/c726872858ce14e793a26619bd6a358f#file-customwhitespacematcher-js-L2 | |
const { diffStringsUnified } = require('jest-diff'); | |
const { | |
matcherHint, | |
printExpected, | |
printReceived | |
} = require('jest-matcher-utils'); | |
const replaceWhitespace = str => | |
str | |
.replace(/(\r\n|\n|\r)/gm, '') | |
.replace(/\s+/g, '') | |
.trim(); | |
const compressWhitespace = arr => arr.map(replaceWhitespace); | |
const name = `toMatchIgnoreWhitespace`; | |
expect.extend({ | |
toMatchIgnoreWhitespace(received, expected) { | |
const [ | |
receivedWithCompresssedWhitespace, | |
expectedWithCompresssedWhitespace | |
] = compressWhitespace([received, expected]); | |
const pass = | |
receivedWithCompresssedWhitespace === expectedWithCompresssedWhitespace; | |
const message = pass | |
? () => | |
`${matcherHint(`.not.${name}`)}\n\n` + | |
`Uncompressed expected value:\n` + | |
` ${printExpected(expected)}\n` + | |
`Expected value with compressed whitespace to not equal:\n` + | |
` ${printExpected(expectedWithCompresssedWhitespace)}\n` + | |
`Uncompressed received value:\n` + | |
` ${printReceived(received)}\n` + | |
`Received value with compressed whitespace:\n` + | |
` ${printReceived(receivedWithCompresssedWhitespace)}` | |
: () => { | |
const diffString = diffStringsUnified( | |
expectedWithCompresssedWhitespace, | |
receivedWithCompresssedWhitespace | |
); | |
return ( | |
`${matcherHint(`.${name}`)}\n\n` + | |
`Uncompressed expected value:\n` + | |
` ${printExpected(expected)}\n` + | |
`Expected value with compressed whitespace to equal:\n` + | |
` ${printExpected(expectedWithCompresssedWhitespace)}\n` + | |
`Uncompressed received value:\n` + | |
` ${printReceived(received)}\n` + | |
`Received value with compressed whitespace:\n` + | |
` ${printReceived(receivedWithCompresssedWhitespace)}${ | |
diffString ? `\n\nDifference:\n\n${diffString}` : `` | |
}` | |
); | |
}; | |
return { | |
actual: received, | |
expected, | |
message, | |
name, | |
pass | |
}; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment