0

I have the following method:

generateKey: () => {
    let key = Math.random()
      .toString(36)
      .substring(2, 10);

    return key;
  }

This method generates a random character string and I wish to unit test it.

After searching how to unit test randomness I've come across the following answers but not a concrete application:

How may I test randomness in this specific case?

Testing the length of the string and its content is simple enough, but testing that values were truly generated randomly seems impossible.

Christopher
  • 1,712
  • 2
  • 21
  • 50
  • 1
    Generate X random items to an array, example test in any language `assert(items.unique.length == X)`. Assume it generates unique items, stop wasting your time on this ;) no method is truly unique. – Mike Doe Dec 03 '18 at 08:43
  • The question does not concern the way I'm generating the key but how to test randomness, which I find interesting to comprehend and learn. :) I've already tested the length of the string itself. – Christopher Dec 03 '18 at 08:47
  • Normally you would mock the `Math.random` function to a expected output, and assert the result of the function when the "random" returns that value. – TryingToImprove Dec 03 '18 at 09:06

1 Answers1

0

For writing tests you need to know input and expected output, so you can assert actual output against expected.

How may I test randomness in this specific case?

When expected output unpredictable you will not be able to tests function in the way this usually done.

You can partially test randomness by executing your function million times and check that no duplicated results were generated.

Fabio
  • 31,528
  • 4
  • 33
  • 72