【问题标题】:Sinon fakeTimers not firingSinon fakeTimers 不触发
【发布时间】:2015-06-24 08:23:51
【问题描述】:

我遇到了 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');
  });

【问题讨论】:

    标签: javascript underscore.js sinon chai


    【解决方案1】:

    问题在于 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;
      };
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      相关资源
      最近更新 更多