Skip to content

Instantly share code, notes, and snippets.

@stephennancekivell
Last active October 5, 2016 09:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephennancekivell/5899425 to your computer and use it in GitHub Desktop.
Save stephennancekivell/5899425 to your computer and use it in GitHub Desktop.
A unit testable version of debounce from underscore.js I think underscore needs a flush feature so we can easily test our applications that use it. A underscore.flush method would allow you to test the different cases without having to make your unit tests slow. This could work similar to angular.js's $httpBackend.flush().
describe('underscore', function(){
it('shouldnt execute immediately', function(){
var hasHappened = false;
var fn = underscore.debounce(function(){
hasHappened = true;
}, 100);
expect(hasHappened).toBe(false);
fn();
expect(hasHappened).toBe(false);
});
it('should execute after delay', function(){
var hasHappened = false;
runs(function(){
var fn = underscore.debounce(function(){
hasHappened = true;
}, 100);
fn();
});
waitsFor(function(){
return hasHappened;
}, 'didnt execute', 200);
runs(function(){
expect(hasHappened).toBe(true);
});
});
it('should only happen once', function(){
var count = 0;
runs(function(){
var fn = underscore.debounce(function(){
count += 1;
}, 100);
fn();
fn();
fn();
});
waitsFor(function(){
return count > 0;
}, 'didnt execute', 200);
runs(function(){
expect(count).toBe(1);
});
});
it('can flush', function(){
var hasHappened = false;
var fn = underscore.debounce(function(){
hasHappened = true;
}, 100);
fn();
underscore.flush();
expect(hasHappened).toBe(true);
});
it('can debounce independent functions', function(){
var aHappened = false;
var bHappened = false;
var a = underscore.debounce(function(){
aHappened = true;
}, 100);
var b = underscore.debounce(function(){
bHappened = true;
}, 100);
a();
b();
underscore.flush();
expect(aHappened).toBe(true);
expect(bHappened).toBe(true);
});
});
var underscore = {};
var timeouts = {};
underscore.debounce = function(fn, delay){
var timeoutId;
return function(){
delete timeouts[timeoutId];
clearTimeout(timeoutId);
timeoutId = setTimeout(function(){
fn();
}, delay);
timeouts[timeoutId] = fn;
};
};
underscore.flush = function(){
for(var timeoutId in timeouts){
timeouts[timeoutId]();
delete timeouts[timeoutId];
clearTimeout(timeoutId);
}
};
@BagrijRoman
Copy link

Thanks. It was very useful for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment