From f82051d7abf9a2137f62cb84f0dd3618397951bc Mon Sep 17 00:00:00 2001 From: Andrew Clark Date: Wed, 17 Apr 2024 13:04:54 -0400 Subject: [PATCH] console test utils fix: match entire string, not just first letter (#28855) Fixes issue where if the first letter of the expected string appeared anywhere in actual message, the assertion would pass, leading to false negatives. We should check the entire expected string. --------- Co-authored-by: Ricky --- .../__tests__/ReactInternalTestUtils-test.js | 22 +++++++++++++++++++ packages/internal-test-utils/consoleMock.js | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/internal-test-utils/__tests__/ReactInternalTestUtils-test.js b/packages/internal-test-utils/__tests__/ReactInternalTestUtils-test.js index af2a447f4981..22f0e0f418cd 100644 --- a/packages/internal-test-utils/__tests__/ReactInternalTestUtils-test.js +++ b/packages/internal-test-utils/__tests__/ReactInternalTestUtils-test.js @@ -2129,6 +2129,28 @@ describe('ReactInternalTestUtils console assertions', () => { `); }); + // @gate __DEV__ + it('regression: checks entire string, not just the first letter', async () => { + const message = expectToThrowFailure(() => { + console.error('Message that happens to contain a "T"\n in div'); + + assertConsoleErrorDev([ + 'This is a completely different message that happens to start with "T"', + ]); + }); + expect(message).toMatchInlineSnapshot(` + "assertConsoleErrorDev(expected) + + Unexpected error(s) recorded. + + - Expected errors + + Received errors + + - This is a complete different message that happens to start with "T" + + Message that happens to contain a "T" " + `); + }); + describe('global withoutStack', () => { // @gate __DEV__ it('passes if errors without stack explicitly opt out', () => { diff --git a/packages/internal-test-utils/consoleMock.js b/packages/internal-test-utils/consoleMock.js index 4601335f40db..3b9ef2f8c0e5 100644 --- a/packages/internal-test-utils/consoleMock.js +++ b/packages/internal-test-utils/consoleMock.js @@ -386,7 +386,7 @@ export function createLogAssertion( expectedWithoutStack = expectedMessageOrArray[1].withoutStack; } else if (typeof expectedMessageOrArray === 'string') { // Should be in the form assert(['log']) or assert(['log'], {withoutStack: true}) - expectedMessage = replaceComponentStack(expectedMessageOrArray[0]); + expectedMessage = replaceComponentStack(expectedMessageOrArray); if (consoleMethod === 'log') { expectedWithoutStack = true; } else {