I have recently dug into building some data generators. Building out what is a personal version of faker that is catered to my own needs. The first thing to generate was random numeric strings. These are strings that only contain numbers, but could also support leading zeros.
Upon trying to test the implementation, one core problem
came to light. Needing to have reproducible random
numbers for specific tests. Previously when this issue has
come about, I’ve implemented an injector to give a function
to make the number. That way in the main code the function
Math.random. While from a test suite, it can be an
anonymous function that gives a static value.
This time I wanted to use some of my recent experience with Sinon to try and do it properly for a web application. Rather than lean on Dependency Injection as my back-end experience has prepared me for; I wanted to continue to write the main code as cleanly as I could.
The solution was to stub
Math.random directly. Then
give it an order of calls with static responses. In the
case of needing to test leading zeros, force the first
number to be a zero and for the rest continue calling
the original function.