How to test a function that output is random using Jest? Like this:
import cuid from 'cuid'; const functionToTest = (value) => ({ [cuid()]: { a: Math.random(), b: new Date().toString(), c: value, } });
So the output of functionToTest('Some predictable value')
will be something like:
{ 'cixrchnp60000vhidc9qvd10p': { a: 0.08715126430943698, b: 'Tue Jan 10 2017 15:20:58 GMT+0200 (EET)', c: 'Some predictable value' }, }
To test a function that returns random numbers you should call it many times and see how many times each number is returned. All that this tests is whether the distribution is rectangular - it doesn't test for (pseudo-)randomness at all.
How to check if a function was called correctly with Jest? To check if a function was called correctly with Jest we use the expect() function with specific matcher methods to create an assertion. We can use the toHaveBeenCalledWith() matcher method to assert the arguments the mocked function has been called with.
In order to run a specific test, you'll need to use the jest command. npm test will not work. To access jest directly on the command line, install it via npm i -g jest-cli or yarn global add jest-cli . Then simply run your specific test with jest bar.
Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.
I used:
beforeEach(() => { jest.spyOn(global.Math, 'random').mockReturnValue(0.123456789); }); afterEach(() => { jest.spyOn(global.Math, 'random').mockRestore(); })
It is easy to add and restores the functionality outside the tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With