【发布时间】:2015-12-14 21:35:12
【问题描述】:
测试使用setTimeout 递归调用自身的 IIFE(立即调用函数表达式)的最佳方法是:
(function myFuncToBeTested() {
// Code to be tested
...
setTimeout(myFuncToBeTested, timeout) // timeout should be checked
})()
我发现以下解决方案将全局 setTimeout 函数替换为 own 存根。这有以下问题:
// 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
}
【问题讨论】:
-
你能窥探
myFuncToBeTested的内容吗?它有任何副作用吗?您打算在测试中断言什么? -
>你能窥探到
myFuncToBeTested的内容吗?实际上不能 -
正如我所提到的,我应该“存根”
setTimeout执行并简单地测试是否已调用setTimeout及其interval。
标签: javascript node.js unit-testing sinon