Sto usando Mocha con Sinon sull'unità test i miei moduli node.js. Ho deriso con successo altre dipendenze (altri moduli che ho scritto), ma mi sono imbattuto in problemi di stub non puri (come Math.random()
e Date.now()
). Ho provato quanto segue (semplificato in modo che questa domanda non sia così localizzata), ma Math.random()
non è stato stubato a causa di un evidente problema di portata. Le istanze di Math
sono indipendenti tra il file di test e mymodule.js
.Stubing Date.now() e Math.random()
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
});
});
});
Quindi, in questo esempio forzato, functThatDependsOnRandom()
sarebbe simile:
mymodule.js
var other = require('./other.js');
function funcThatDependsOnRandom(num) {
if(typeof num === 'undefined') num = Math.random();
return other.otherFunc(num);
}
E 'possibile stub Math.random()
in questo scenario con Sinon?
Ottima risposta. Puoi usare proxyquire invece di mockery. – Wtower