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
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/");
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.
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)
}
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.