Skip to content

Commit f88ab6c

Browse files
authored
perf(expect): reuse the key array in deep equality (#12104)
1 parent ff6b427 commit f88ab6c

2 files changed

Lines changed: 16 additions & 6 deletions

File tree

‎packages/expect/src/jest-utils.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -281,18 +281,19 @@ function isErrorEqual(
281281
}
282282

283283
function keys(obj: object, hasKey: (obj: object, key: string) => boolean) {
284-
const keys = []
284+
const keys: (string | symbol)[] = []
285285

286286
for (const key in obj) {
287287
if (hasKey(obj, key)) {
288288
keys.push(key)
289289
}
290290
}
291-
return keys.concat(
292-
(Object.getOwnPropertySymbols(obj) as Array<any>).filter(
293-
(symbol) => (Object.getOwnPropertyDescriptor(obj, symbol) as PropertyDescriptor).enumerable,
294-
),
295-
)
291+
for (const symbol of Object.getOwnPropertySymbols(obj)) {
292+
if (Object.getOwnPropertyDescriptor(obj, symbol)!.enumerable) {
293+
keys.push(symbol)
294+
}
295+
}
296+
return keys
296297
}
297298

298299
function hasDefinedKey(obj: any, key: string) {

‎test/unit/test/jest-expect.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,15 @@ describe('jest-expect', () => {
414414
)
415415
})
416416

417+
it('toEqual checks symbol enumerability', () => {
418+
const visible = Symbol('visible')
419+
const hidden = Symbol('hidden')
420+
const received = Object.defineProperty({ a: 1, [visible]: 2 }, hidden, { value: 3 })
421+
422+
expect(received).toEqual({ a: 1, [visible]: 2 })
423+
expect(received).not.toEqual({ a: 1, [visible]: 3 })
424+
})
425+
417426
it('fails cleanly when toHaveProperty receives a nullish value', () => {
418427
expect(() => expect(null).toHaveProperty('value')).toThrowErrorMatchingInlineSnapshot(
419428
`[TypeError: .toHaveProperty() expects to receive a valid object, but got null]`,

0 commit comments

Comments
 (0)