【问题标题】:toBeCloseTo equivalent for recursive equality test in JesttoBeCloseTo 等效于 Jest 中的递归相等测试
【发布时间】:2017-04-24 22:08:44
【问题描述】:

我有两个对象,我想使用 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)。

【问题讨论】:

    标签: javascript object testing numbers jestjs


    【解决方案1】:

    我最终得到了以下解决方案:

    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 }
      },
    })
    

    【讨论】:

    • 我为我的代码调整了一些东西:const { getType } = this.utils 到 const getType = type => typeof type; 和 expect(round(received)).toEqual(expected) 到 expect(round(received)).toEqual(round(expected))
    • 使用 Jest 26,此代码不再有效(getType 不再在 this.utils 上公开)。正如@AJarofClay 提到的,定义自己的很容易,但是我们还必须考虑数组(因为typeof anArray === 'object')。更好的定义是const getType = x => Array.isArray(x) ? 'array' : typeof x;
    猜你喜欢
    • 1970-01-01
    • 2018-01-20
    • 2019-09-06
    • 2010-12-27
    • 2016-12-01
    • 1970-01-01
    • 2017-09-01
    • 2022-08-09
    • 2021-09-24
    相关资源
    最近更新 更多