Last active
May 20, 2020 12:13
-
-
Save arthurdenner/3c9b2c087e98ad19e8d3ca14e0be6b89 to your computer and use it in GitHub Desktop.
Jest custom `toMatch` with string normalization
This file contains 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
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