fix debounce
This commit is contained in:
parent
80f2becc95
commit
844b96a821
1 changed files with 22 additions and 23 deletions
|
@ -1,48 +1,47 @@
|
||||||
describe("debounce", function() {
|
describe('debounce', function () {
|
||||||
before(function() {
|
before(function () {
|
||||||
this.clock = sinon.useFakeTimers();
|
this.clock = sinon.useFakeTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
after(function() {
|
after(function () {
|
||||||
this.clock.restore();
|
this.clock.restore();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("for one call - runs it after given ms", function () {
|
it('for one call - runs it after given ms', function () {
|
||||||
const f = sinon.spy();
|
const f = sinon.spy();
|
||||||
const debounced = debounce(f, 1000);
|
const debounced = debounce(f, 1000);
|
||||||
|
|
||||||
debounced("test");
|
debounced('test');
|
||||||
assert(f.notCalled);
|
assert(f.notCalled, 'not called immediately');
|
||||||
this.clock.tick(1000);
|
this.clock.tick(1000);
|
||||||
assert(f.calledOnceWith("test"));
|
assert(f.calledOnceWith('test'), 'called after 1000ms');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("for 3 calls - runs the last one after given ms", function() {
|
it('for 3 calls - runs the last one after given ms', function () {
|
||||||
const f = sinon.spy();
|
const f = sinon.spy();
|
||||||
const debounced = debounce(f, 1000);
|
const debounced = debounce(f, 1000);
|
||||||
|
|
||||||
f("a")
|
debounced('a');
|
||||||
setTimeout(() => f("b"), 200); // ignored (too early)
|
setTimeout(() => debounced('b'), 200); // ignored (too early)
|
||||||
setTimeout(() => f("c"), 500); // runs (1000 ms passed)
|
setTimeout(() => debounced('c'), 500); // runs (1000 ms passed)
|
||||||
this.clock.tick(1000);
|
this.clock.tick(1000);
|
||||||
|
|
||||||
assert(f.notCalled);
|
assert(f.notCalled, 'not called after 1000ms');
|
||||||
|
|
||||||
this.clock.tick(500);
|
this.clock.tick(500);
|
||||||
|
|
||||||
assert(f.calledOnceWith('c'));
|
assert(f.calledOnceWith('c'), 'called after 1500ms');
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps the context of the call", function() {
|
it('keeps the context of the call', function () {
|
||||||
let obj = {
|
let obj = {
|
||||||
f() {
|
f() {
|
||||||
assert.equal(this, obj);
|
assert.equal(this, obj);
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
obj.f = debounce(obj.f, 1000);
|
obj.f = debounce(obj.f, 1000);
|
||||||
obj.f("test");
|
obj.f('test');
|
||||||
this.clock.tick(5000);
|
this.clock.tick(5000);
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue