I need to do some expectation in Jasmine, like:
let realValue = callSomeMethod();
let expected = [{
total: 33,
saved: 1.65
}];
expect(realValue).toEqual(expected);
But it fails, and the message is:
Expect [ Object({ total: 33, saved: 1.6500000000000001 })]
to equal [Object({ total: 33, saved: 1.65 })].
How can I do the right checking?
To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.
Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.
Because floating point arithmetic is different from real number arithmetic. Bottom line: Never use == to compare two floating point numbers. Here's a simple example: double x = 1.0 / 10.0; double y = x * 10.0; if (y !=
Yes. It's safe. Note it's a double rather than a float here - but the same rules apply.
The toBeCloseTo
matcher is for precision math comparison:
expect(1.6500000000000001).toBeCloseTo(1.65, 2);
expect(1.6500000000000001).toBeCloseTo(1.65, 15);
expect(1.6500000000000001).not.toBeCloseTo(1.65, 16);
source: Jasmine matchers
In the case some properties are floats and some are not:
let realValue = callSomeMethod();
let expectedFloat = {
saved: 1.65,
otherFloat: 6.44
}
let expectedOther = {
firstName: 'Paul',
total: 33,
};
let expected = {
...expectedFloat,
...expectedOther
}
let floatNames = Object.getOwnPropertyNames(expectedFloat);
const testFloatProperty = (name) => () => {
expect(realValue[name]).toBeCloseTo(expectedFloat[name], 3)
}
for (let i in floatNames) {
it('should be close to expected ' + floatNames[i], testFloatProperty(floatNames[i]));
}
it('should contain other expected props', function() {
expect(realValue).toEqual(jasmine.objectContaining(expectedOther))
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With