toBeCloseTo等效于Jest

时间:2016-12-09 12:13:18

标签: javascript object testing numbers jestjs

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

1 个答案:

答案 0 :(得分:3)

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

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