Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 881
O.O. Avatar asked Dec 15 '19 11:12

O.O.


2 Answers

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();
like image 171
CertainPerformance Avatar answered Oct 15 '22 13:10

CertainPerformance


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)
like image 41
maazadeeb Avatar answered Oct 15 '22 13:10

maazadeeb