如何在JavaScript中使用Math.random进行测试? [英] How to test with Math.random in JavaScript?

查看:80
本文介绍了如何在JavaScript中使用Math.random进行测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数可以选择最小值和最大值之间的随机值。因此,当我进行测试时,我测试该值落在最小值和最大值之间。但是因为在我的应用程序中有些失败,测试通过了一些时间,有些时候由于随机性而失败。

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 there where some failures in my app the test passed some times and some times fails due to the randomness.

覆盖/模拟<$是一个好主意c $ c> Math.random()返回0和1并测试我的值是否与最大值或最小值相同?或者有没有更好的方法来测试JavaScript中的随机性?

Would it be a good idea to override/mock Math.random() to return 0 and 1 and test that my value is same as max or min value? Or are there better ways to test randomness in JavaScript?

这是用于创建随机数的函数:

Here is the function that will be used to create the random number:

function constrain(min, max){
    return Math.round(Math.random() * (max - min) + min)
}


推荐答案

SinonJS 是一个JavaScript 模拟框架,它集成了与所有主要的JavaScript单元测试框架。适配器将负责恢复您在测试期间创建的任何存根/模拟。

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/");

这篇关于如何在JavaScript中使用Math.random进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆