Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest toBeCloseTo for objects

I want to check two matrices that are approximately equal.

In jest, we have toEqual to check two equality of two objects, but cannot compare its floating number properties that are approximately equal; we also have toBeCloseTo, but it can only compare two floating numbers rather than apply the approximate equality strategy to all floating number property in an object.

I don't want to compare every floating number property by hand, because this may lose the verbose result that shows the diff of two objects. (The matrix object also contains other non-floating number fields, e.g. strings)

Is there a better way to compare two matrices approximately? How can I do that?

like image 375
Jakob Avatar asked Mar 03 '26 15:03

Jakob


1 Answers

This can be solved with the closeTo method of the AsymmetricMatchers in expect like so:

function createGreyScaleRgb(num) {
  return { red: num / 255, green: num / 255, blue: num / 255 };
}

const expected = {
  red: expect.closeTo(0.75),
  green: expect.closeTo(0.75),
  blue: expect.closeTo(0.75),
};

expect(createGreyScaleRGB(192)).toEqual(expected);
like image 56
Krisztián Balla Avatar answered Mar 06 '26 04:03

Krisztián Balla