Skip to content

Instantly share code, notes, and snippets.

@phartenfeller
Created August 8, 2020 11:39
Show Gist options
  • Save phartenfeller/f099773b29c6dfce15f650b874600837 to your computer and use it in GitHub Desktop.
Save phartenfeller/f099773b29c6dfce15f650b874600837 to your computer and use it in GitHub Desktop.
Jest custom matcher that ignores whitespace and new lines
// 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