How to test with Math.random in JavaScript?

前端 未结 3 778
花落未央
花落未央 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:30

    SinonJS is a JavaScript mocking framework which integrates with all of the major JavaScript Unit Testing frameworks. The adapters will take care of 'reverting' any stubs / mocks that you create during your tests.

    // Stub out Math.random so it always returns '4' (chosen by fair dice roll)
    sinon.stub(Math, 'random').returns(4);
    
    // Double check that it worked.
    equal(Math.random(), 4, "http://xkcd.com/221/");
    
    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2021-01-05 09:50

    Generally your tests should pass for all possible values of your non-deterministic code. Maybe have a loop in your test where you do the test say 100 times. That will catch more failures without changing the application code. What you suggested is also an option.

    0 讨论(0)
提交回复
热议问题