Here is one that compresses all whitespace down to a single space for readability based on Jest’s toEqual matcher. It will deal with tabs, newlines etc. It will give you pretty output like the included Jest matchers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import { replace, map, equals } from 'ramda'; import { matcherHint, printReceived, printExpected } from 'jest-matcher-utils'; import diff from 'jest-diff'; const replaceWhitespace = replace(/\s+/g, ` `); const compressWhitespace = map(replaceWhitespace); const name = `toEqualWithCompressedWhitespace`; export default (received, expected) => { const [ receivedWithCompresssedWhitespace, expectedWithCompresssedWhitespace, ] = compressWhitespace([received, expected]); const pass = equals( 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, { expand: this.expand, } ); 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, }; }; |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.