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

邮差的信 提交于 2019-12-23 07:27:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!