toBeCloseTo 等效于 Jest 中的递归相等性测试
toBeCloseTo equivalent for recursive equality test in Jest
我有两个对象,我想使用 Jest 测试递归相等性。这很简单:
test('should be recursively equal', () => {
const test = { x: 0, y: 0 }
const expected = { x: 0, y: 0 }
expect(test).toEqual(expected)
})
但在某些情况下会出现问题;如您所知,JavaScript 计算浮点数非常糟糕,因此有时测试会变成以下内容:
test('should be recursively equal', () => {
const test = { x: 0.00000000001, y: 0 }
const expected = { x: 0, y: 0 }
expect(test).toEqual(expected)
})
它不再起作用了。 Jest 提供了 toBeCloseTo
测试,它以数字和精度作为参数,但我想知道递归等式是否有等价物(类似于 toEqualCloseTo
)。
我最终得到了以下解决方案:
expect.extend({
toEqualCloseTo(received, expected, precision = 3) {
const { getType } = this.utils
function round(obj) {
switch (getType(obj)) {
case 'array':
return obj.map(round)
case 'object':
return Object.keys(obj).reduce((acc, key) => {
acc[key] = round(obj[key])
return acc
}, {})
case 'number':
return +obj.toFixed(precision)
default:
return obj
}
}
expect(round(received)).toEqual(expected)
return { pass: true }
},
})
我有两个对象,我想使用 Jest 测试递归相等性。这很简单:
test('should be recursively equal', () => {
const test = { x: 0, y: 0 }
const expected = { x: 0, y: 0 }
expect(test).toEqual(expected)
})
但在某些情况下会出现问题;如您所知,JavaScript 计算浮点数非常糟糕,因此有时测试会变成以下内容:
test('should be recursively equal', () => {
const test = { x: 0.00000000001, y: 0 }
const expected = { x: 0, y: 0 }
expect(test).toEqual(expected)
})
它不再起作用了。 Jest 提供了 toBeCloseTo
测试,它以数字和精度作为参数,但我想知道递归等式是否有等价物(类似于 toEqualCloseTo
)。
我最终得到了以下解决方案:
expect.extend({
toEqualCloseTo(received, expected, precision = 3) {
const { getType } = this.utils
function round(obj) {
switch (getType(obj)) {
case 'array':
return obj.map(round)
case 'object':
return Object.keys(obj).reduce((acc, key) => {
acc[key] = round(obj[key])
return acc
}, {})
case 'number':
return +obj.toFixed(precision)
default:
return obj
}
}
expect(round(received)).toEqual(expected)
return { pass: true }
},
})