Skip to content

Instantly share code, notes, and snippets.

@cassidoo
Last active February 21, 2023 20:12
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cassidoo/c726872858ce14e793a26619bd6a358f to your computer and use it in GitHub Desktop.
Save cassidoo/c726872858ce14e793a26619bd6a358f to your computer and use it in GitHub Desktop.
A custom matcher for when you want to compare strings in Jest and ignore whitespace
// Modified version of this Stack Overflow response:
// https://stackoverflow.com/a/48459005/1950503
// (Removes ramda dependency, adds .trim() to string replacer, adds it to Jest global var instead of exporting)
// To use:
// Put `<rootDir>/path/to/customWhitespaceMatcher.js` in your Jest config under setupFiles
// Call it in your tests like this:
// expect(
// customMatchers.whitespaceMatcher(receivedResult, expectedResult).pass
// ).toBeTruthy();
import { matcherHint, printReceived, printExpected } from 'jest-matcher-utils';
import diff from 'jest-diff';
const replaceWhitespace = str => str.replace(/\s+/g, ' ').trim();
const compressWhitespace = arr => arr.map(replaceWhitespace);
const name = `toEqualWithCompressedWhitespace`;
const whitespaceMatcher = (received, expected) => {
const [
receivedWithCompresssedWhitespace,
expectedWithCompresssedWhitespace
] = compressWhitespace([received, expected]);
let 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 = diff(
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
};
};
global.customMatchers = { whitespaceMatcher };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment