我正在尝试在 Jest 中使用 toBeCloseTo
来测试 float :
expect(value).toBeCloseTo(0.01491, 5);
但是当我运行测试时,我看到了这个结果:
Precision: 5-digit
Expected: 0.01491
Received: 0.01491570355
当我将精度设置为 4
时,测试通过了,但我很困惑。在documentation ,它说:
Use
numDigits
to control how many digits after the decimal point to check
所以,我在这里假设我正在比较正确的位数:我有 .01491
,它有 5
位数,所以我期望(双关有意!)测试以准确比较这些数字并通过。
我在这里错过了什么?
谢谢
最佳答案
actual comparison code used by Jest's toBeCloseTo
method如下:
expectedDiff = Math.pow(10, -precision) / 2;
receivedDiff = Math.abs(expected - received);
pass = receivedDiff < expectedDiff;
(奇怪的是,文档将第二个参数 precision
改为 numDigits
。)
所以你的测试失败了,因为期望值和实际值之间的差异超过了 0.5 × 10−5:大约是 0.57 × 10−5。四舍五入到小数点后五位,接收到的值0.01491570355
为0.01492
。
据我所知,这样的比较背后的逻辑是,如果预期值是您从将实际值四舍五入到 numDigits
个小数位。
关于javascript - 开 Jest toBeCloseTo 的精度没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50896753/