最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to compare two objects with float values in jasmine? - Stack Overflow

programmeradmin0浏览0评论

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
  • 1 I don't know enough about jasmine, but in general computing, comparing two floats with precision should be done by testing nearness within some threshold, i.e abs(realValue - expected) < epsilon – danh Commented Jul 21, 2016 at 15:37
Add a comment  | 

2 Answers 2

Reset to default 17

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))
})
发布评论

评论列表(0)

  1. 暂无评论