Ich verwende Mocha mit Sinon Unit-Test meine node.js Module. Ich habe andere Abhängigkeiten erfolgreich verspottet (andere Module, die ich geschrieben habe), aber ich habe Probleme beim Stoppen nicht reiner Funktionen (wie Math.random()
und Date.now()
). Ich habe Folgendes versucht (vereinfacht, so dass diese Frage nicht so lokalisiert ist), aber Math.random()
wurde nicht wegen eines offensichtlichen Umfangs Problems gestempelt. Die Instanzen von Math
sind unabhängig zwischen der Testdatei und mymodule.js
.Stubbing Date.now() und 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
});
});
});
Also in diesem erfundenen Beispiel würde functThatDependsOnRandom()
wie folgt aussehen:
mymodule.js
var other = require('./other.js');
function funcThatDependsOnRandom(num) {
if(typeof num === 'undefined') num = Math.random();
return other.otherFunc(num);
}
Ist es möglich, Math.random()
Stub in Dieses Szenario mit Sinon?
Ausgezeichnete Antwort. Sie können Proxy-Quotes anstelle von Spott verwenden. – Wtower