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.
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])
)
}
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