Does toBeCloseTo work for arrays?

Skip to first unread message

Eric Borts

unread,
Mar 1, 2014, 6:08:49 PM3/1/14
to jasmi...@googlegroups.com
I'm trying to compare two arrays of floating point numbers, and I can't get toBeCloseTo(<array>, <epsilon>) to work properly:

[code]
        expectedWeights = [0.372, 1.860];
        expect(actual.k).toBeCloseTo(expectedWeights, 1);

[results]
Expected [ 0.37209302325581395, 1.86046511627907 ] to be close to [ 0.372, 1.86 ], 1.

So I'm forced to iterate over the values doing toBeCloseTo on each of them.

I'm new to Jasmine, so pardon my ignorance. But I couldn't find this answer anywhere.

Thanks!

Sheel Choksi

unread,
Mar 4, 2014, 12:53:57 AM3/4/14
to jasmi...@googlegroups.com
toBeCloseTo does not currently work for arrays. You can find the implementation here: https://github.com/pivotal/jasmine/blob/v2.0.0/src/core/matchers/toBeCloseTo.js which deals directly with floats. We prefer to keep the built in matchers as simple as possible so that they're easy to understand, without overloading them to handle many types with slightly different behavior. 

If you find yourself needing to do this sort of comparison often, I recommend taking advantage of custom matchers. A custom matcher will allow you to keep your tests readable, handle the iteration in only one place, and provide your own custom failure message that can quickly point you to the test failure. More about custom matchers is documented here: http://jasmine.github.io/2.0/custom_matcher.html

Hopefully that works for your use case!
Sheel
Reply all
Reply to author
Forward
0 new messages