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);
?
Zero is neither positive nor negative.
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.
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.
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.
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!
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.
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