From 3ffcd2ea6256e5d01259d724d9e5782f3d422c75 Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa Date: Tue, 13 Feb 2024 16:27:03 +0900 Subject: [PATCH] fix(utils): fix asymmetric matcher diff inside array (#5189) --- packages/utils/src/error.ts | 2 +- test/core/test/diff.test.ts | 66 +++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/packages/utils/src/error.ts b/packages/utils/src/error.ts index ff9bd37afa7b..9d6f5b548677 100644 --- a/packages/utils/src/error.ts +++ b/packages/utils/src/error.ts @@ -141,7 +141,7 @@ function isAsymmetricMatcher(data: any) { function isReplaceable(obj1: any, obj2: any) { const obj1Type = getType(obj1) const obj2Type = getType(obj2) - return obj1Type === obj2Type && obj1Type === 'Object' + return obj1Type === obj2Type && (obj1Type === 'Object' || obj1Type === 'Array') } export function replaceAsymmetricMatcher(actual: any, expected: any, actualReplaced = new WeakSet(), expectedReplaced = new WeakSet()) { diff --git a/test/core/test/diff.test.ts b/test/core/test/diff.test.ts index bff339b5960c..18c3f2ec9a98 100644 --- a/test/core/test/diff.test.ts +++ b/test/core/test/diff.test.ts @@ -1,6 +1,7 @@ import { expect, test, vi } from 'vitest' import { getDefaultColors, setupColors } from '@vitest/utils' import { diff } from '@vitest/utils/diff' +import { processError } from '@vitest/runner' import { displayDiff } from '../../../packages/vitest/src/node/error' test('displays object diff', () => { @@ -59,3 +60,68 @@ test('display multiline line string diff', () => { " `) }) + +test('asymmetric matcher in object', () => { + setupColors(getDefaultColors()) + expect(getErrorDiff({ x: 0, y: 'foo' }, { x: 1, y: expect.anything() })).toMatchInlineSnapshot(` + "- Expected + + Received + + Object { + - "x": 1, + + "x": 0, + "y": Anything, + }" + `) +}) + +test('asymmetric matcher in array', () => { + setupColors(getDefaultColors()) + expect(getErrorDiff([0, 'foo'], [1, expect.anything()])).toMatchInlineSnapshot(` + "- Expected + + Received + + Array [ + - 1, + + 0, + Anything, + ]" + `) +}) + +test('asymmetric matcher in nested', () => { + setupColors(getDefaultColors()) + expect( + getErrorDiff( + [{ x: 0, y: 'foo' }, [0, 'bar']], + [{ x: 1, y: expect.anything() }, [1, expect.anything()]], + ), + ).toMatchInlineSnapshot(` + "- Expected + + Received + + Array [ + Object { + - "x": 1, + + "x": 0, + "y": Anything, + }, + Array [ + - 1, + + 0, + Anything, + ], + ]" + `) +}) + +function getErrorDiff(actual: unknown, expected: unknown) { + try { + expect(actual).toEqual(expected) + } + catch (e) { + const error = processError(e) + return error.diff + } + expect.unreachable() +}