Ant*_*ois 5 javascript testing numbers object jestjs
我有两个对象,我想使用 Jest 测试递归相等性。这很简单:
test('should be recursively equal', () => {
const test = { x: 0, y: 0 }
const expected = { x: 0, y: 0 }
expect(test).toEqual(expected)
})
Run Code Online (Sandbox Code Playgroud)
但在某些情况下会出现问题;如您所知,JavaScript 计算浮点数非常糟糕,因此有时测试会变成以下内容:
test('should be recursively equal', () => {
const test = { x: 0.00000000001, y: 0 }
const expected = { x: 0, y: 0 }
expect(test).toEqual(expected)
})
Run Code Online (Sandbox Code Playgroud)
它不再起作用了。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 }
},
})
Run Code Online (Sandbox Code Playgroud)
我最终得到了以下解决方案:
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 }
},
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1144 次 |
最近记录: |