【问题标题】:Testing IIFE with setTimeout使用 setTimeout 测试 IIFE
【发布时间】: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


【解决方案1】:

这个函数可以做成对象吗?

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 );

【讨论】:

  • 我认为您应该让start() 返回this,或者在单独的语句中调用myObject.start()。照原样,myObject 在您的代码 sn-p 中将是 undefined
【解决方案2】:

我想建议在 thedarklord47 的答案和您的存根实验 setTimeout 之间采用混合解决方案。像您这样的 IIFE 本质上很难测试,因为您没有留下任何方法来检查它是否已被调用。您可以按如下方式修改您的 API:

var repeater = {
  start: function () {
    this.func();

    setTimeout(this.start.bind(this), timeout);
  },
  func: function () {
    // code to be tested
  }
};

然后你的测试可能看起来像这样(因为你用 标记我已经使用它,特别是它的假计时器 API,它可以让你检查你的间隔功能):

// setup
var clock = sinon.useFakeTimers();
var spy = sinon.spy(repeater, 'func');

// test
repeater.start();
assert(spy.calledOnce);

// advance clock to trigger timeout
clock.tick(timeout);
assert(spy.calledTwice);

// advance clock again
clock.tick(timeout);
assert(spy.calledThrice);

// teardown
clock.restore();
spy.restore();

【讨论】:

    猜你喜欢
    • 2014-07-26
    • 2018-03-24
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多