【问题标题】:Fuzzy floating point checks against mock call argumnets in JestJest 中针对模拟调用参数的模糊浮点检查
【发布时间】:2021-12-15 14:04:12
【问题描述】:

给定一个带有签名的函数

interface Position {
  x: number, y: number
}

function f(position: Position): void { … }

我想在测试中模拟它

// given
const f = jest.fn()

// when
// exercise SUT

// then
expect(f).toHaveBeenCalledWith<Position>({x: 1.0, y: 1.0});

但不幸的是,我正在处理浮点数,所以我需要检查以留出一些余地。现在,我可以

expect(f.mock.calls[0][0].x).toBeCloseTo(1, 1);
expect(f.mock.calls[0][0].y).toBeCloseTo(1, 1);

但这会很快变老真实。 Jest 维护者don't seem to think warrants inclusion in Jest 有一张票,match using expect 有一个包,但它没有做我想做的事!类似于:

expect(f).toHaveBeenCalledWith(
  expect.objectContaining({
    x: expect.numberCloseTo(1), 
    y: expect.numberCloseTo(1)
   });

有类似的东西还是我必须自己动手?

【问题讨论】:

  • 不,没有内置的,但你可以添加自己的 expect.extend

标签: javascript typescript jestjs


【解决方案1】:

正如 Aleksey 已经暗示的那样,我需要编写自己的自定义匹配器。所以,就这样吧:

declare global {
  namespace jest {
    interface Expect {
      numberCloseTo(expected: number, precision?: number): any;
    }
  }
}

expect.extend({
  numberCloseTo(actual: number, expected: number, precision: number = 2) {
    expect(actual).toBeCloseTo(expected, precision);
    return { message: () => "This shouldn't happen.", pass: true };
  },
});

我是这样使用它的:

expect(f).toHaveBeenCalledWith(
  expect.objectContaining<Position>({
    x: expect.numberCloseTo(1, 1),
    y: expect.numberCloseTo(1, 1),
  })
);

扩展已经存在的匹配器在 Jest 中是非常尴尬的,我猜that's by design。所以我们需要包含一个虚拟消息。

如果您使用的是 Flow 或纯 JS,则只能删除 TS declare global 等。

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 1970-01-01
    • 2019-12-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 2019-07-22
    相关资源
    最近更新 更多