jest: [Bug]: 0 is not considered equal to -0?

Version

27.4.7

Steps to reproduce

it(`these are the same. No really `, () => {
  expect(0 === -0).toBe(true); 
  expect(0).toBe(-0);
})

First test passes, because it should. Second test fails. It very much should not.

Expected behavior

By both maths and JS spec definition, 0 is equal to -0

Actual behavior

    Expected: -0
    Received: 0

       7 |   it(`these are the same. No really `, () => {
       8 |     expect(0 === -0).toBe(true);
    >  9 |     expect(0).toBe(-0);
         |               ^
      10 |   })

Additional context

Floating point numbers result in hilarious edge cases.

Environment

Win 10 Pro x64, Node v17.3.0, Jest v27.4.7

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 1
  • Comments: 19 (3 by maintainers)

Most upvoted comments

And again.

Given that I’m running into this as part of a maths library tests, 0 and -0 kind of need to be the same thing. The direction by which we arrive at zero is not part of the numerical equality. It’s why 0 === -0 is true as per the JS language spec (ref: https://262.ecma-international.org/6.0/#sec-strict-equality-comparison, 7.2.13 step 4, points d and e) even if in the IEEE 754 spec the values +0 and -0 are provisioned as different bit patterns.

(Jest is a test framework for JS, after all; not the IEEE =)

Using Object.is in this case gives you the wrong result because while they’re different internal values to JS (because otherwise it wouldn’t be able to show 0 vs. -0) the JS spec says they’re the same value in actual code. As such, treating them as not equal is quite literally a spec violation.

Of course, if a toStrictEqual or the like goes “hey these are different IEEE values” that makes a lot of sense, and even a maths library might benefit from that (e.g. to determine limiting behaviour) but the plain equals/toBe should most definitely say “yes, these are the same value”.