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?
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?
Share Improve this question asked Jul 21, 2016 at 15:34 FreewindFreewind 198k163 gold badges452 silver badges733 bronze badges 1 |2 Answers
Reset to default 17The 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))
})
abs(realValue - expected) < epsilon
– danh Commented Jul 21, 2016 at 15:37