Skip to content

Commit

Permalink
test($mdUtil): add tests for throttle()
Browse files Browse the repository at this point in the history
Follow-up on angular#977.
  • Loading branch information
gkalpak committed Jan 20, 2015
1 parent b809f47 commit 332bedb
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/core/util/util.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,58 @@ describe('util', function() {
$rootScope.$broadcast('event');
expect(spy).toHaveBeenCalled();
}));

describe('throttle', function() {
var delay = 500;
var nowMockValue;
var originalFn;
var throttledFn;

beforeEach(inject(function($mdUtil) {
$mdUtil.now = function () { return nowMockValue; };
originalFn = jasmine.createSpy('originalFn');
throttledFn = $mdUtil.throttle(originalFn, delay);
nowMockValue = 1; // Not 0, to prevent `!recent` in `throttle()` to evaluate to true
// even after `recent` has been set
}));

it('should immediately invoke the function on first call', function() {
expect(originalFn).not.toHaveBeenCalled();
throttledFn();
expect(originalFn).toHaveBeenCalled();
});

it('should not invoke the function again before (delay + 1) milliseconds', function() {
throttledFn();
expect(originalFn.callCount).toBe(1);

throttledFn();
expect(originalFn.callCount).toBe(1);

nowMockValue += delay;
throttledFn();
expect(originalFn.callCount).toBe(1);

nowMockValue += 1;
throttledFn();
expect(originalFn.callCount).toBe(2);
});

it('should pass the context to the original function', inject(function($mdUtil) {
var obj = {
called: false,
fn: function() { this.called = true; }
};
var throttled = $mdUtil.throttle(obj.fn, delay);

expect(obj.called).toBeFalsy();
throttled.call(obj);
expect(obj.called).toBeTruthy();
}));

it('should pass the arguments to the original function', function() {
throttledFn(1, 2, 3, 'test');
expect(originalFn).toHaveBeenCalledWith(1, 2, 3, 'test');
});
});
});

0 comments on commit 332bedb

Please sign in to comment.