Andreas Köberle Andreas Köberle - 2 years ago 108
Javascript Question

How to test with Math.random in JavaScript?

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 there where some failures in my app the test passed some times and some times fails due to the randomness.

Would it be a good idea to override/mock

Math.random()
to return 0 and 1 and test that my value is same as max or min value? Or are there better ways to test randomness in JavaScript?

Here is the function that will be used to create the random number:

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

Answer Source

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/");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download