test.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. var assert = require('assert');
  2. var throttle = require('./');
  3. describe('throttle', function(){
  4. function counter() {
  5. function count(){
  6. count.invoked++;
  7. }
  8. count.invoked = 0;
  9. return count;
  10. }
  11. it('should throttle a function', function(done){
  12. var count = counter();
  13. var wait = 100;
  14. var total = 500;
  15. var fn = throttle(count, wait);
  16. var interval = setInterval(fn, 20);
  17. setTimeout(function(){
  18. clearInterval(interval);
  19. assert(count.invoked === (total / wait));
  20. done();
  21. }, total + 5);
  22. });
  23. it('should call the function last time', function(done){
  24. var count = counter();
  25. var wait = 100;
  26. var fn = throttle(count, wait);
  27. fn();
  28. fn();
  29. assert(count.invoked === 1);
  30. setTimeout(function(){
  31. assert(count.invoked === 2);
  32. done();
  33. }, wait + 5);
  34. });
  35. it('should pass last context', function(done){
  36. var wait = 100;
  37. var ctx;
  38. var fn = throttle(logctx, wait);
  39. var foo = {};
  40. var bar = {};
  41. fn.call(foo);
  42. fn.call(bar);
  43. assert(ctx === foo);
  44. setTimeout(function(){
  45. assert(ctx === bar);
  46. done();
  47. }, wait + 5);
  48. function logctx() {
  49. ctx = this;
  50. }
  51. });
  52. it('should pass last arguments', function(done){
  53. var wait = 100;
  54. var args;
  55. var fn = throttle(logargs, wait);
  56. fn.call(null, 1);
  57. fn.call(null, 2);
  58. assert(args && args[0] === 1);
  59. setTimeout(function(){
  60. assert(args && args[0] === 2);
  61. done();
  62. }, wait + 5);
  63. function logargs() {
  64. args = arguments;
  65. }
  66. });
  67. });