Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expect an array of float numbers to be close to another array in Jasmine

I'm testing a Javascript function returning an array of numbers, to see if the returned array contains the same elements as the array containing the expected output:

expect(myArray).toEqual(expectedArray);

This works flawlessly if myArray and expectedArray only contain integers, but fail if there is at least one float present, due to floating-point precision errors. toBeCloseTo does not seem to function on arrays.

Currently I'm doing a loop to to do member-wise checking:

for (var i = 0; i < myArray.length; i++) {
    expect(myArray[i]).toBeCloseTo(expectedArray[i]);
}

... but is there a cleaner way to do this? If the test fails for whatever reason, the output is bloated with a hideous amount of error messages.

like image 643
John Weisz Avatar asked Feb 10 '16 14:02

John Weisz


1 Answers

The following code should answer your question:

function expectToBeCloseToArray(actual, expected) {
  expect(actual.length).toBe(expected.length)
  actual.forEach((x, i) =>
    expect(x).withContext(`[${i}]`).toBeCloseTo(expected[i])
  )
}
like image 78
Yas Avatar answered Oct 16 '22 14:10

Yas