From 516a2fabffb8ad6cdc95153e2fe43fe938955ebe Mon Sep 17 00:00:00 2001 From: ibuibu Date: Sat, 11 Mar 2023 16:12:47 +0900 Subject: [PATCH] implement checkZeroWidthSpace --- packages/expect/src/matchers.ts | 10 +++++--- packages/jest-matcher-utils/src/index.ts | 30 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/packages/expect/src/matchers.ts b/packages/expect/src/matchers.ts index 0ea9c04501ae..9b31f55ddc34 100644 --- a/packages/expect/src/matchers.ts +++ b/packages/expect/src/matchers.ts @@ -26,6 +26,7 @@ import { MatcherHintOptions, RECEIVED_COLOR, SUGGEST_TO_CONTAIN_EQUAL, + checkZeroWidthSpace, ensureExpectedIsNonNegativeInteger, ensureNoExpected, ensureNumbers, @@ -131,7 +132,8 @@ const matchers: MatchersObject = { EXPECTED_LABEL, RECEIVED_LABEL, isExpand(this.expand), - ) + ) + + checkZeroWidthSpace(received, expected) ); }; @@ -641,7 +643,8 @@ const matchers: MatchersObject = { EXPECTED_LABEL, RECEIVED_LABEL, isExpand(this.expand), - ); + ) + + checkZeroWidthSpace(received, expected); // Passing the actual and expected objects so that a custom reporter // could access them, for example in order to display a custom visual diff, @@ -978,7 +981,8 @@ const matchers: MatchersObject = { EXPECTED_LABEL, RECEIVED_LABEL, isExpand(this.expand), - ); + ) + + checkZeroWidthSpace(received, expected); // Passing the actual and expected objects so that a custom reporter // could access them, for example in order to display a custom visual diff, diff --git a/packages/jest-matcher-utils/src/index.ts b/packages/jest-matcher-utils/src/index.ts index e910f7a99039..4d239e5877f0 100644 --- a/packages/jest-matcher-utils/src/index.ts +++ b/packages/jest-matcher-utils/src/index.ts @@ -582,3 +582,33 @@ export const matcherHint = ( return hint; }; + +export const checkZeroWidthSpace = ( + received: unknown, + expected: unknown, +): string => { + const createNote = (str: string, isReceived: boolean): string | undefined => { + // eslint-disable-next-line no-misleading-character-class + const zwspRegExp = RegExp( + '[\\u001c-\\u001f\\u11a3-\\u11a7\\u180e\\u200b-\\u200f\\u2060\\u3164\\u034f\\u202a-\\u202e\\u2061-\\u2063\\ufeff]', + ); + + const pos = str.search(zwspRegExp); + if (pos !== -1) { + return `Note: A zero-width space exists at index ${pos - 1} of ${ + isReceived ? 'Received' : 'Expected' + }.`; + } + return undefined; + }; + + const note = + createNote(stringify(received), true) || + createNote(stringify(expected), false); + + if (note) { + return `\n${chalk.yellow(note)}`; + } else { + return ''; + } +};