I tried to create a jest test in ts, where the result should equal 0. This seems to fail on -0.
test("zero equals fails", () => {
const actual = -0
const expected = 0
// expect(actual).toBe(expected)
// expect(actual).toStrictEqual(expected)
// expect(actual).toEqual(expected)
})
Gives:
Expected: 0
Received: -0
This even though the equals check in my console say they are equal.
0 == -0
true
0 === -0
true
What assert comparison should I use in this case?
All of those methods use Object.is
to compare primitive values, and Object.is
fails when comparing 0
to -0
.
There doesn't seem to be any specific relevant method for this (there's toBeCloseTo
, but that's not so appropriate, since the issue isn't floating-point precision).
A possible alternative is:
expect(actual === expected).toBeTruthy();
The previous answers already talk about Object.is
, which jest uses internally for comparisons. You could tweak your test to use Math.abs
on -0.
expect(Math.abs(actual)).toBe(expected)
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