Back to Repositories

Testing Throttle Function Implementation in Parcel Bundler

This test suite validates the throttle utility function implementation in Parcel, ensuring proper function invocation timing and context preservation. The tests verify throttling behavior, interval management, and proper ‘this’ binding.

Test Coverage Overview

The test suite provides comprehensive coverage of the throttle utility’s core functionality.

  • Function invocation frequency control
  • Interval-based execution timing
  • Context preservation testing
  • Edge case handling for multiple rapid calls

Implementation Analysis

The testing approach utilizes Jest’s describe/it pattern combined with Sinon for spy and time manipulation capabilities. The implementation demonstrates clean isolation of test cases with precise timing control through Sinon’s fake timers.

  • Sinon spy implementation for call tracking
  • Fake timer manipulation for interval testing
  • Context binding verification

Technical Details

  • Testing Framework: Jest
  • Assertion Library: Node’s assert
  • Mocking Library: Sinon
  • Time Control: Sinon fake timers
  • Flow type checking enabled with strict-local mode

Best Practices Demonstrated

The test suite exhibits several testing best practices including isolation of concerns, proper setup and teardown of time-sensitive tests, and comprehensive edge case coverage.

  • Clear test case isolation
  • Proper cleanup of fake timers
  • Specific assertion checks
  • Meaningful test descriptions

parcel-bundler/parcel

packages/core/utils/test/throttle.test.js

            
// @flow strict-local

import assert from 'assert';
import sinon from 'sinon';
import throttle from '../src/throttle';

describe('throttle', () => {
  it("doesn't invoke a function more than once in a given interval", () => {
    let spy = sinon.spy();
    let throttled = throttle(spy, 100);

    throttled(1);
    throttled(2);
    throttled(3);

    assert(spy.calledOnceWithExactly(1));
  });

  it('calls the underlying function again once the interval has passed', () => {
    let time = sinon.useFakeTimers();
    let spy = sinon.spy();
    let throttled = throttle(spy, 100);

    throttled(1);
    throttled(2);
    throttled(3);

    time.tick(100);
    throttled(4);
    assert.deepEqual(spy.args, [[1], [4]]);

    time.restore();
  });

  it('preserves the `this` when throttled functions are invoked', () => {
    let result;
    let throttled = throttle(function () {
      result = this.bar;
    }, 100);

    throttled.call({bar: 'baz'});
    assert(result === 'baz');
  });
});