O.O.
O.O.

Reputation: 868

Javascript jest expect 0 equal -0

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

Answers (4)

trincot
trincot

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

Pranav C Balan
Pranav C Balan

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

maazadeeb
maazadeeb

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

CertainPerformance
CertainPerformance

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

Related Questions