Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test floating-point equality using chai?

We're using Chai's BDD API to write unit tests.

How can we assert floating point equality?

For example, if I try to make this assertion to check for a 66⅔% return value:

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 
like image 899
zigg Avatar asked Sep 24 '15 20:09

zigg


People also ask

What is chai in testing?

Chai is an assertion library that is mostly used alongside Mocha. It can be used both as a BDD / TDD assertion library for NodeJS and can be paired with any JavaScript testing framework.

What are the 3 interfaces of the Chai assertion library?

Chai supports 3 different assertion styles: expect , should , and assert . expect is most common, because should modifies Object.


2 Answers

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 of 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.

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.

like image 56
GolezTrol Avatar answered Sep 27 '22 20:09

GolezTrol


The within assertion can be used to check whether a floating-point number is close to its intended result:

expect(percentage).to.be.within(66.666, 66.667); 
like image 27
zigg Avatar answered Sep 27 '22 20:09

zigg