gpt4 book ai didi

backbone.js - 如何使用 Sinon fakeTimer 在 Jasmine 中测试 LoDash 去抖动?

转载 作者:行者123 更新时间:2023-12-04 14:44:16 24 4
gpt4 key购买 nike

我正在尝试编写一个测试来消除搜索查询中的用户输入。该函数在主干 View 上定义:

SearchView = Backbone.View.extend({
events: {
"input .search-input": "search"
},

// init, render, etc.

search: _.debounce(function() {
this.collection.fetch();
}, 200)
});

本来Backbone库(v0.9.10)使用的是Underscore(v1.4.4),测试定义如下:
describe("SearchView", function() {
var view, $viewContainer;

beforeEach(function() {
appendSetFixtures('<div class="jasmine-container"></div>');
$viewContainer = $(".jasmine-container");

view = new SearchView({
el: $viewContainer
});
});

afterEach(function() {
view.remove();
view.cleanup();
});

//...

describe("wires the search input", function() {
var collectionStub,
fakeTimer;

beforeEach(function() {
collectionStub = sinon.stub(
SearchResultsCollection.prototype,
"fetch"
);

fakeTimer = sinon.useFakeTimers();
});

afterEach(function() {
collectionStub.restore();
fakeTimer.restore();
});

it("should not trigger a search before 200ms", function() {
fakeTimer.tick(199);
expect(collectionStub).not.toHaveBeenCalled();
});

it("should trigger a search after 200ms", function() {
fakeTimer.tick(200);
expect(collectionStub).toHaveBeenCalled();
});
});
});

但是,现在我想合并 LoDash 而不是 Underscore。使用他们网站上最新的 Underscore 兼容性构​​建(LoDash 2.4.1/Underscore 1.5.6),除了使用 _.debounce 的测试外,我所有的测试都通过了!

我做了一些研究,发现了这些 relevant issues使用 runInContext 创建 LoDash Underscore 构建,但由于缺乏示例,我不知道如何使用它。我如何使用 _.runInContext()在我的规范中使用 sinon.fakeTimer ?

最佳答案

SearchView = Backbone.View.extend({
events: {
"input .search-input": function() {
this.search();
}
},

initialize: function() {
this.search = _.debounce(this.search, 200);
}

// init, render, etc.

search: function() {
this.collection.fetch();
}
});

describe("SearchView", function() {
var view;
var $viewContainer;
var clock;
var lodash = window._;

beforeEach(function() {
appendSetFixtures('<div class="jasmine-container"></div>');
$viewContainer = $(".jasmine-container");

clock = sinon.useFakeTimers();
window._ = _.runInContext(window);

view = new SearchView({
el: $viewContainer
});
});

afterEach(function() {
view.remove();
view.cleanup();

clock.restore();
window._ = lodash;
});

//...

describe("wires the search input", function() {
var collectionStub;

beforeEach(function() {
collectionStub = sinon.stub(
SearchResultsCollection.prototype,
"fetch"
);
});

afterEach(function() {
collectionStub.restore();
});

it("should not trigger a search before 200ms", function() {
fakeTimer.tick(199);
expect(collectionStub).not.toHaveBeenCalled();
});

it("should trigger a search after 200ms", function() {
fakeTimer.tick(200);
expect(collectionStub).toHaveBeenCalled();
});
});
});

关于backbone.js - 如何使用 Sinon fakeTimer 在 Jasmine 中测试 LoDash 去抖动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26662353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com