测试使用 setTimeout
递归调用自身的 IIFE(立即调用函数表达式)的最佳方法是什么:
(function myFuncToBeTested() {
// Code to be tested
...
setTimeout(myFuncToBeTested, timeout) // timeout should be checked
})()
我找到了以下解决方案,用自己的
stub 替换全局setTimeout
函数。这有以下问题:
// Saving original setTimeout. This should be restored in test cleanup
originalSetTimeout = global.setTimeout
// Replace with function
global.setTimeout = function setImmediate(myFunc, interval) {
// FIXME: This function now always called
// Save interval to be tested
savedInterval = interval
}
最佳答案
这个函数可以做成一个对象吗?
var myObject = (function(){
function start(){
myFuncToBeTested();
setTimeout(start, 10);
return this;
}
function myFunctToBeTested(){
//Code to be tested
}
return {
start: start,
myFuncToBeTested: myFuncToBeTested
}
})().start();
然后您可以使用您选择的测试框架来测试:
assert( myObject.myFuncToBeTested() == expectedValue );
关于javascript - 使用 setTimeout 测试 IIFE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34277043/