Sinon fakeTimers 不触发

Sinon fakeTimers not firing

我对 sinon 的 fakeTimers 有疑问。这用于具有 Marionette.js、下划线和 chai 测试运行程序的环境中。如果我在 chrome 中设置断点并遍历,我的计时器将被触发。但是,如果我不设置断点,它就永远不会被触发。

我正在使用 _.debounce,这会导致设置计时器。

计时器的设置方式如下:

describe('Basket item view', function() {
  beforeEach(function() {
    this.clock = sinon.useFakeTimers();

    this.app = new Backbone.Marionette.Application();
    this.app.addInitializer(basketInit);
    this.app.start(basketOptions);

    this.basketListView = this.app.baskets.currentView;
    this.basketViews = this.basketListView.children;
  });

  afterEach(function() {
    this.app = this.basketListView = null;
    this.clock.restore();
  });

  it('updates amount on quantity change', function() {
    var basketLayoutView = this.basketViews.last();
    var itemView = basketLayoutView.basket.currentView.children.first();
    var items = basketLayoutView.collection;
    var item = items.findWhere({id: 136});

    var $quantity = itemView.$('input.quantity');

    var updatedQuantity = 2;
    var updatedPrice = '20.00';

    $quantity.val(updatedQuantity);
    $quantity.change();

    this.clock.tick(500);

    var newItemView = basketLayoutView.basket.currentView.children.first();
    var $amount = newItemView.$('td.amount.total');
    assert.equal(
        item.get('quantity'), updatedQuantity,
        'quantity change');

    assert.equal(
        $amount.text().trim(), updatedPrice,
        'amount change');
  });

问题出在 Underscore.js 和 _.debounce 函数上。它试图通过比较日期变得更加准确,这很好,打破了 sinon 的测试。

为了解决这个问题,我只是用以前的版本覆盖了去抖功能:

_.debounce = function(func, wait, immediate) {
  var timeout, result;
  return function() {
    var context = this, args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) result = func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) result = func.apply(context, args);
    return result;
  };
};