How to test with Math.random in JavaScript?

前端 未结 3 777
花落未央
花落未央 2021-01-05 09:21

I have a function that will select a random value between a min and a max value. So when I have a test where I test that the value fall between the min and max value. But as

3条回答
  •  一生所求
    2021-01-05 09:41

    Preferrably, you should have no random element in your test at all. You should feed your method known values, so that you can determine if the result is exactly what you excpect.

    If you have random values, you would have to test the method a lot of times, and you are still not sure that you get the exact result that you want, only that you get something in the right range.

    If you for example use the current date in your code (new Date()), then you should provide your method with known dates when testing, otherwise your test will only show that the method works right now. Tomorrow it might fail.


    Edit:

    However, I can tell you right away that your method doesn't work well. You should use the floor method instead of round, otherwise the lowest and highest values will occur half as often as the other values:

    function constrain(min, max){
      return Math.floor(Math.random() * (max - min + 1) + min)
    }
    

提交回复
热议问题