【问题标题】:Include toBeCloseTo in Jest .toMatchObject在 Jest .toMatchObject 中包含 toBeCloseTo
【发布时间】:2019-04-21 12:06:24
【问题描述】:

我正在测试一个对象是否匹配一组字段,但其中一个是浮点数,我需要使用.toBeCloseTo。如何在一个expect 内完成?

expect(foo).toMatchObject({
  bar: 'baz',
  value: ???.toBeCloseTo(5),  // TODO
});

我可以使用expect(foo.value).toBeCloseTo(5),但我不想将逻辑分解为多个expects,每个浮点数一个。

【问题讨论】:

  • expect(foo.value).toBeCloseTo(Math.round(foo.value)); 我猜是这样的。

标签: javascript unit-testing jestjs


【解决方案1】:

问题

docs for toMatchObject 声明“您可以将属性与值或匹配器进行匹配”。

很遗憾,toBeCloseTo 目前不能用作非对称匹配器,它看起来像 these are the only asymmetric matchers currently provided by Jest


解决方案

如果您使用的是 Jest v23 或更高版本,您可以创建自己的,基本上是使用 expect.extend 复制 toBeCloseTo

expect.extend({
  toBeAround(actual, expected, precision = 2) {
    const pass = Math.abs(expected - actual) < Math.pow(10, -precision) / 2;
    if (pass) {
      return {
        message: () => `expected ${actual} not to be around ${expected}`,
        pass: true
      };
    } else {
      return {
        message: () => `expected ${actual} to be around ${expected}`,
        pass: false
      }
    }
  }
});

const foo = {
  bar: 'baz',
  value: 4.9999
};

test('foo', () => {
  expect(foo.value).toBeAround(5, 3);  // SUCCESS in Jest > v20
  expect(foo).toMatchObject({
    bar: 'baz',
    value: expect.toBeAround(5, 3)  // SUCCESS only in Jest > v23
  });
});

请注意,expect.extend 创建的匹配器只能在 Jest v23 及更高版本中用于 toMatchObject 等函数中。


替代解决方案

来自 Jest 合作者的 this post:“虽然它是隐含的但目前没有记录,但 Jest 断言将非对称匹配器对象评估为 defined in Jasmine”。

使用the logic from toBeCloseTo 的非对称匹配器可以这样创建:

const closeTo = (expected, precision = 2) => ({
  asymmetricMatch: (actual) => Math.abs(expected - actual) < Math.pow(10, -precision) / 2
});

const foo = {
  bar: 'baz',
  value: 4.9999
};

test('foo', () => {
  expect(foo).toMatchObject({
    bar: 'baz',
    value: closeTo(5, 3)  // SUCCESS
  });
});

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-07-27
  • 2017-04-24
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 2020-01-01
  • 2021-01-14
  • 1970-01-01
相关资源
最近更新 更多