Skip to content

Instantly share code, notes, and snippets.

@arthurdenner
Last active May 20, 2020 12:13
Show Gist options
  • Save arthurdenner/3c9b2c087e98ad19e8d3ca14e0be6b89 to your computer and use it in GitHub Desktop.
Save arthurdenner/3c9b2c087e98ad19e8d3ca14e0be6b89 to your computer and use it in GitHub Desktop.
Jest custom `toMatch` with string normalization
import { matcherHint, printReceived, printExpected } from 'jest-matcher-utils';
const matches = (received: string, expected: string | RegExp) =>
typeof expected === 'string'
? received.includes(expected)
: expected.test(received);
const normalize = (text: string) => text.replace(/\s+/g, ' ').trim();
expect.extend({
toMatchNormalized(received: string, expected: string | RegExp) {
const isString = typeof expected === 'string';
const exp = isString ? normalize(expected as string) : expected;
const rec = normalize(received);
const checkEmptyStrings = exp !== '' && rec === '';
return {
pass: !checkEmptyStrings && matches(rec, exp),
message: () => {
const to = this.isNot ? 'not ' : '';
const typeExpected = isString ? 'substring' : 'pattern';
const labelExpected = `Expected ${typeExpected}: ${to}`;
const labelReceived = `Received string: ${' '.repeat(
typeExpected.length - 6 + to.length
)}`;
return [
matcherHint('toMatchNormalized'),
`\n\n`,
`${labelExpected}${printExpected(expected)}\n`,
`${labelReceived}${printReceived(received)}`,
].join('');
},
};
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment