How to test with Math.random in JavaScript?

前端 未结 3 809
花落未央
花落未央 2021-01-05 09:21

I have a function that will select a random value between a min and a max value. So when I have a test where I test that the value fall between the min and max value. But as

3条回答
  •  长情又很酷
    2021-01-05 09:30

    SinonJS is a JavaScript mocking framework which integrates with all of the major JavaScript Unit Testing frameworks. The adapters will take care of 'reverting' any stubs / mocks that you create during your tests.

    // Stub out Math.random so it always returns '4' (chosen by fair dice roll)
    sinon.stub(Math, 'random').returns(4);
    
    // Double check that it worked.
    equal(Math.random(), 4, "http://xkcd.com/221/");
    

提交回复
热议问题