मैं MochaSinon के साथ अपने node.js मॉड्यूल का परीक्षण करने के लिए उपयोग कर रहा हूं। मैंने सफलतापूर्वक अन्य निर्भरताओं (अन्य मॉड्यूल जो मैंने लिखे हैं) का मज़ाक उड़ाया है, लेकिन मैंने गैर-शुद्ध कार्यों (जैसे Math.random()
और Date.now()
) को दबाकर समस्याओं में भाग लिया है। मैंने निम्नलिखित की कोशिश की है (सरलीकृत है कि यह प्रश्न इतना स्थानीय नहीं है), लेकिन Math.random()
को स्पष्ट दायरे की समस्या के कारण स्कब नहीं किया गया था। Math
के उदाहरण परीक्षण फ़ाइल और mymodule.js
के बीच स्वतंत्र हैं।स्टबिंग दिनांक .now() और 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
});
});
});
तो यह काल्पनिक उदाहरण में, functThatDependsOnRandom()
दिखाई देगा:
mymodule.js
var other = require('./other.js');
function funcThatDependsOnRandom(num) {
if(typeof num === 'undefined') num = Math.random();
return other.otherFunc(num);
}
यह संभव में Math.random()
ठूंठ है साइनऑन के साथ यह परिदृश्य?
उत्कृष्ट जवाब। आप मजाकिया के बजाय प्रॉक्सीक्वायर का भी उपयोग कर सकते हैं। – Wtower