Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make jest not distinguish between negative zero and positive zero?

What is the best way to make Jest pass the following test:

test('example', () => {
  expect(0).toEqual(-0);
});

I don't want to distinguish negative zero and positive zero.


Maybe I should use some other function instead of .toEqual? Or I should replace all blocks like this:

expect(a).toEqual(b);

to

expect(a === 0 ? +0 : a).toEqual(b === 0 ? +0 : b);

?

like image 527
diralik Avatar asked Jan 23 '18 15:01

diralik


People also ask

Is negative zero the same as positive zero?

Zero is neither positive nor negative.

Why is there a negative zero in JavaScript?

The name for this is Signed Zero. It turns out the reason that JavaScript has -0 is because it is a part of the IEEE 754 floating-point specification. Two zeroes are also present in other languages like Ruby as well.

What is deep equality in jest?

toEqual when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity—this is also known as "deep equal". For example, toEqual and toBe behave differently in this test suite, so all the tests pass.

Is negative 0 a number?

Negative numbers are less than 0 and located to the left of 0 on a number line. The number zero is neither positive nor negative. Positive and negative numbers are sometimes called signed numbers.


2 Answers

You can slightly sidestep the issue by doing your logic inside of the expect function:

expect(0).toEqual(-0); // fails
expect(0 === -0).toEqual(true); // ugly, but it works!
like image 69
Sandy Gifford Avatar answered Sep 17 '22 16:09

Sandy Gifford


A solution for lists and nested objects would be to convert them to JSON and back.

const negativeObject = { list: [-0, -0] };
const positiveObject = { list: [0, 0] };

expect(JSON.parse(JSON.stringify(negativeObject)))
  .toEqual(positiveObject);

This works because JSON.stringify() converts -0 to 0.

like image 35
tiz Avatar answered Sep 20 '22 16:09

tiz