Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a function that output is random using Jest?

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'   }, } 
like image 954
Bogdan Slovyagin Avatar asked Jan 10 '17 13:01

Bogdan Slovyagin


People also ask

How do you know if a function is random?

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 do you test a function is called in Jest?

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.

How do you run a test with Jest?

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.

What is mocking in unit testing Jest?

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.


1 Answers

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.

like image 139
Rui Fonseca Avatar answered Oct 12 '22 00:10

Rui Fonseca