简体   繁体   English

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

[英]How can I test floating-point equality using chai?

We're using Chai's BDD API to write unit tests.我们使用Chai 的 BDD API来编写单元测试。

How can we assert floating point equality?我们如何断言浮点相等?

For example, if I try to make this assertion to check for a 66⅔% return value:例如,如果我尝试使用此断言来检查 66⅔% 的返回值:

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

I get this failure:我得到这个失败:

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

I was looking for this too, and apart from this question, I also found this discussion regarding a feature request that led to the addition ofcloseTo .我也在寻找这个,除了这个问题,我还发现了有关导致添加closeTo的功能请求的讨论 With that you can specify a value and a +/- delta, so basically it lets you specify the precision with which to check the result.有了它,您可以指定一个值和一个 +/- delta,因此基本上它可以让您指定检查结果的精度。

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

or或者

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

or或者

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

It's not perfect of course, because this will approve any number from 6.665 to 6.667.这当然不是完美的,因为这将批准从 6.665 到 6.667 的任何数字。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM