Testing Randomness
How do you solve testing when using randomization? Values will by design be indeterministic, so what is a good way of knowing your program is doing the expected thing?
One of my clever colleagues, Orphis, mentioned in the bypassing the other day a tip about mocking random with a predictably seeded random. JavaScript lends itself very well to this, since we can inject a mock into the Math object.
For my project I set up a tiny random-mock lib using the mocking library Sinon. We could very easily do this with vanilla JS too, but using Sinon allows us to check how many times Math.random() have been called, restore the mock, and more useful things.
To create my predictable randomness mock I simply utilize the return value of the Math.sine-function from it’s 5th decimal with an every increasing input. Each time the random mock is called, you get a new, predictable, Math.random()-compatible number.
You can read more about that idea and rationalization at this Stack Overflow article.
You can apply this mock by importing the random-mock lib and running it’s exported mock() function. After that, everything using Math.random() looks random but is deterministic and can be tested.
Lastly I want to give an example of how this is applied. Below is the function being tested — a random string generator to create ids for example.
And here is the test suite that tests the function.
I’m very excited about using this in my system tests for when enemies drop power ups and enemy AI.