问题
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.
回答1:
The following code should answer your question:
actual.every((x, i) => expect(x).toBeCloseTo(expected[i]));
回答2:
Try this:
for (let i=0; i<returnedArray.length; i++){
if(expectedArray.indexOf(returnedArray[i]) === -1 ){
console.log("not a match")
break;
}else{
console.log("it's a match")
break;
}
}
来源:https://stackoverflow.com/questions/35318278/expect-an-array-of-float-numbers-to-be-close-to-another-array-in-jasmine