Math.random()
和Date.now()
)时遇到了问题。我尝试了以下方法(简化后,以使此问题不再局限于特定情况),但由于明显的作用域问题,Math.random()
没有被stubbed。在测试文件和mymodule.js
之间,Math
的实例是独立的。
test.js
var sinon = require('sinon'),
mymodule = require('./mymodule.js'),
other = require('./other.js');
describe('MyModule', function() {
describe('funcThatDependsOnRandom', function() {
it('should call other.otherFunc with a random num when no num provided', function() {
sinon.mock(other).expects('otherFunc').withArgs(0.5).once();
sinon.stub(Math, 'random').returns(0.5);
funcThatDependsOnRandom(); // called with no args, so should call
// other.otherFunc with random num
other.verify(); // ensure expectation has been met
});
});
});
在这个人为的例子中,
functThatDependsOnRandom()
看起来像这样:
mymodule.js
var other = require('./other.js');
function funcThatDependsOnRandom(num) {
if(typeof num === 'undefined') num = Math.random();
return other.otherFunc(num);
}
在这种情况下,使用Sinon是否可以对
Math.random()
进行存根处理?