Jest: Close comparison between float numbers within objects

Created on 25 May 2017  Â·  7Comments  Â·  Source: facebook/jest


Do you want to request a feature or report a bug?

Feature request

What is the current behavior?

.toEqual doesn't provide close comparison between float numbers within objects. I'm aware of toBeCloseTo but it's just too much work for me to unpack all the sub (and sub-sub) properties within the object I want to test.

What is the expected behavior?

Maybe .toEqual could receive another parameter for the precision tolerated by tests, or maybe another explicit matcher like .toEqualWithFloats could be added.

Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.

That's reproducible with the default jest configuration. I'm using jest v19.0.2.

Test case

test('compare floats within objects', () => {
  expect({ a: 0.30000000000000004 }).toEqualWithFloats({ a: 0.3 });
});

Most helpful comment

All 7 comments

@thymikee it's slightly different from my proposal. The link you provided only does that for a single value, I have an object with lots of properties that contain floats. unpacking each value and testing it would be really laborious. do you think it makes sense? I edited the description to be more specific. Thank you for the answer!

I don't see the reason we should add this kind of matcher, as this use case is very specific.
And Jest also has expect.extend just for such occasions — to create your own matcher, useful inside your tests.

Fair enough. I just have tons of tables with floats because I'm building a UI for charts!

I was trying to reuse the jest tooling to create my own matcher via extend but I'd have to copy and paste code or write my own traversal function. I ended up just hardcoding some piece of data in my test so it always generates the same values and then toEqual becomes useful again.

Thanks for the response!

Also see #4058

Nice! Thanks @clawconduce

Was this page helpful?
0 / 5 - 0 ratings