Testing impure functions

For starters, we'll go back to our getRandomLetter() function. With insider knowledge about its implementation (this is called white box testing, in opposition to black box testing, in which we know nothing about the function code itself) we can spy (a Jasmine term) on the Math.random() method, and set a mock function that will return whatever values we desire.

We can revisit some of the test cases we did in the previous section. In the first case, we set Math.random() to return 0.0001, and we test that it was actually called, and also that the final return was A.  In the second case, just for variety, we set things up so Math.random() can be called twice, returning two different values. We also verify that there ...

Get Mastering Javascript Functional Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.