Reputation: 868
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?
Upvotes: 7
Views: 6410
Reputation: 350270
That is the consequence of how Object.is
works. You could do as follows (assuming expected
is not -0):
expect(actual === 0 ? 0 : actual).toBe(expected)
Upvotes: 1
Reputation: 115222
Jest is internally using Object.is
method to assert the value so it will be false.
console.log(Object.is(0, -0))
Refer : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
You can extend and implement new method to use ===
(Strict Equality Comparison) or ==
(Abstract Equality Comparison) instead of Object.is
( SameValue) method.
expect.extend({
toBeEqCustom(received, expected) {
if (received === expected) {
return {
message: () => `expected ${received} not to be ${expected}`,
pass: true,
};
} else {
return {
message: () =>
`expected ${received} to be ${expected}`,,
pass: false,
};
}
},
});
// and use it like
expect(actual).toBeEqCustom(expected);
Upvotes: 1
Reputation: 6112
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)
Upvotes: 1
Reputation: 370769
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();
Upvotes: 5