如何使用 chai 测试浮点相等性?

How can I test floating-point equality using chai?

我们正在使用 Chai's BDD API 编写单元测试。

我们如何断言浮点数相等?

例如,如果我尝试做出此断言来检查 66⅔% return 值:

expect(percentage).to.equal(2 / 3 * 100.0);

我失败了:

AssertionError: expected 66.66666666666667 to equal 66.66666666666666
Expected :66.66666666666666
Actual   :66.66666666666667

within 断言可用于检查浮点数是否接近其预期结果:

expect(percentage).to.be.within(66.666, 66.667);

我也在找这个,除了这个问题,我还找到了this discussion regarding a feature request that led to the addition of closeTo。有了它,您可以指定一个值和一个 +/- 增量,因此基本上它可以让您指定检查结果的精度。

percentage.should.be.closeTo(6.666, 0.001);

// `closeTo` is an alias for the arguably better name `approximately`
percentage.should.be.approximately(6.666, 0.001);

expect(percentage).to.be.closeTo(6.666, 0.001)

当然它并不完美,因为这将批准从 6.665 到 6.667 的任何数字。