小编Ant*_*ois的帖子

toBeCloseTo 等效于 Jest 中的递归相等测试

我有两个对象,我想使用 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 } = …
Run Code Online (Sandbox Code Playgroud)

javascript testing numbers object jestjs

5
推荐指数
1
解决办法
1144
查看次数

标签 统计

javascript ×1

jestjs ×1

numbers ×1

object ×1

testing ×1