我对 sinon 的 fakeTimers 有疑问。这是在具有 Marionette.js、underscore 和 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;
};
};
关于javascript - 诗农 fakeTimers 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31021398/