Search code examples
javascriptunit-testingjestjs

Jest: Testing random position of an array


After some research, I found out that mocking will allow me to test random values. However, how do I test the value of a random position (needle) picked up on an array (haystack)?

For instance, how do you test this code with Jest?

var words = ['Hey', 'Hello', 'Hi'];
var random = Math.floor( Math.random() * (words.length - 1) + 0 );
var word = words[random];

Solution

  • While this doesn't necessarily test against Math.random, in this case I think this can be tested by simply checking the values.

    function pick(words) {
      var random = Math.floor( Math.random() * (words.length - 1) + 0 );
      return words[random];
    }
    
    expect(pick(['Hey', 'Hello', 'Hi'])).toMatch(/Hey|Hello|Hi/)