Skip to content

Commit

Permalink
fix(utils): fix asymmetric matcher diff inside array (#5189)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa committed Feb 13, 2024
1 parent 7d18233 commit 3ffcd2e
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/utils/src/error.ts
Expand Up @@ -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()) {
Expand Down
66 changes: 66 additions & 0 deletions 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', () => {
Expand Down Expand Up @@ -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()
}

0 comments on commit 3ffcd2e

Please sign in to comment.