Jest中对象数组深度相等断言失败问题求助
Jest测试对象匹配失败问题排查
我在使用Jest测试代码时,预期对象与接收对象看起来完全一致,但测试始终提示不匹配。
测试输出
Expected: ArrayContaining [{"buildingScores": ObjectContaining {"coast": Any<Number>, "fluvial": Any<Number>, "pluvial": Any<Number>}, "buildings": ArrayContaining [ObjectContaining {"id": Any<Number>, "score": Any<Number>, "scores": ObjectContaining {"coast": Any<Number>, "fluvial": Any<Number>, "pluvial": Any<Number>}}], "builidngScore": Any<Number>, "capakey": Any<String>, "createdAt": StringMatching /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/, "owners": ArrayContaining [Any<String>], "plotScore": Any<Number>, "plotScores": ObjectContaining {"coast": Any<Number>, "fluvial": Any<Number>, "pluvial": Any<Number>}, "updatedAt": StringMatching /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/, "zones": ObjectContaining {"bank": Any<Boolean>, "risk": Any<Boolean>, "signalArea": Any<Boolean>}}] Received: [{"buildingScores": {"coast": 0, "fluvial": 0, "pluvial": 1}, "buildings": [{"id": 5723528, "score": 1, "scores": {"coast": 0, "fluvial": 0, "pluvial": 1}}, {"id": 6113163, "score": 0, "scores": {"coast": 0, "fluvial": 0, "pluvial": 0}}], "builidngScore": 1, "capakey": "44017A0860/00G002", "createdAt": 2022-12-28T12:58:12.319Z, "owners": "{\"WATERING OUDE KALE EN MEIREBEEK\"}", "plotScore": 2, "plotScores": {"coast": 0, "fluvial": 0, "pluvial": 2}, "updatedAt": 2022-12-28T12:58:12.319Z, "zones": {"bank": false, "risk": false, "signalArea": false}}]
断言语句
expect(scores).toEqual(expect.arrayContaining([expectedFloodScoreObject]))
预期对象定义
export const expectedFloodScoreObject = { createdAt: expect.stringMatching(DATE_REGEX), updatedAt: expect.stringMatching(DATE_REGEX), capakey: expect.any(String), owners: expect.arrayContaining([expect.any(String)]), zones: expect.objectContaining({ risk: expect.any(Boolean), bank: expect.any(Boolean), signalArea: expect.any(Boolean) }), plotScore: expect.any(Number), plotScores: expect.objectContaining({ pluvial: expect.any(Number), fluvial: expect.any(Number), coast: expect.any(Number) }), builidngScore: expect.any(Number), buildingScores: expect.objectContaining({ pluvial: expect.any(Number), fluvial: expect.any(Number), coast: expect.any(Number) }), buildings: expect.arrayContaining([ expect.objectContaining({ id: expect.any(Number), score: expect.any(Number), scores: expect.objectContaining({ pluvial: expect.any(Number), fluvial: expect.any(Number), coast: expect.any(Number) }) }) ]) }
日期正则
export const DATE_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/
问题原因
核心不匹配点在owners字段:
- 预期断言要求
owners是字符串数组(expect.arrayContaining([expect.any(String)])) - 实际接收值是JSON格式的字符串(
"{\"WATERING OUDE KALE EN MEIREBEEK\"}"),属于单个字符串,不符合数组预期。
注:预期对象里的builidngScore拼写与接收值一致,因此不是问题。
解决方法
根据业务逻辑二选一:
- 如果
owners应该是数组:在业务代码中把该JSON字符串解析为数组,比如用JSON.parse(owners)处理后再返回。 - 如果
owners确实是JSON字符串:修改预期对象的owners断言,改为expect.any(String),或者更精确的expect.stringMatching(/^\{.*\}$/)来匹配JSON结构的字符串。
内容的提问来源于stack exchange,提问作者Stephen
相关产品推荐
相关产品推荐

