Я использую Mocha с Sinon для модульного тестирования моих модулей node.js. Я успешно имитировал другие зависимости (другие написанные мной модули), но столкнулся с проблемами, заглушающими нечистые функции (например, Math.random()
и Date.now()
). Я пробовал следующее (упрощенное, чтобы этот вопрос не был таким локализованным), но Math.random()
не был заглушен из-за очевидной проблемы с областью действия. Экземпляры Math
независимы между тестовым файлом и mymodule.js
.
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);
}
Можно ли в этом сценарии заглушить Math.random()
Синон?