Back to Repositories

Testing Scheduler Priority Management in PreactJS

This test suite validates the scheduler functionality in Preact’s compatibility layer, focusing on priority-based task execution and timing utilities. The tests ensure proper callback handling across different priority levels and verify the timestamp functionality.

Test Coverage Overview

The test suite covers two main components of the Preact scheduler: runWithPriority and unstable_now functions.

Key functionality tested includes:
  • Callback execution across five priority levels (Idle, Low, Normal, UserBlocking, Immediate)
  • Timestamp generation and validation
  • Priority-based task scheduling verification

Implementation Analysis

The testing approach uses Jest and Sinon for spy functionality to track callback executions. The tests implement a systematic verification of the scheduler’s priority system, using individual test cases for each priority level and timestamp validation.

Technical patterns include:
  • Spy-based callback tracking
  • Sequential priority level testing
  • Type and value assertions for timestamp verification

Technical Details

Testing tools and setup:
  • Jest test framework
  • Sinon for spy functionality
  • Preact/compat scheduler module
  • Chai-style assertions (expect)
  • Describe/it block structure for test organization

Best Practices Demonstrated

The test suite demonstrates several testing best practices including isolated test cases, clear test descriptions, and comprehensive priority level coverage. Notable practices include:
  • Systematic priority level testing
  • Clear test case isolation
  • Explicit assertion messages
  • Proper spy usage for callback verification
  • Type and value validation for timestamps

preactjs/preact

compat/test/browser/scheduler.test.js

            
import {
	unstable_runWithPriority,
	unstable_NormalPriority,
	unstable_LowPriority,
	unstable_IdlePriority,
	unstable_UserBlockingPriority,
	unstable_ImmediatePriority,
	unstable_now
} from 'preact/compat/scheduler';

describe('scheduler', () => {
	describe('runWithPriority', () => {
		it('should call callback ', () => {
			const spy = sinon.spy();
			unstable_runWithPriority(unstable_IdlePriority, spy);
			expect(spy.callCount).to.equal(1);

			unstable_runWithPriority(unstable_LowPriority, spy);
			expect(spy.callCount).to.equal(2);

			unstable_runWithPriority(unstable_NormalPriority, spy);
			expect(spy.callCount).to.equal(3);

			unstable_runWithPriority(unstable_UserBlockingPriority, spy);
			expect(spy.callCount).to.equal(4);

			unstable_runWithPriority(unstable_ImmediatePriority, spy);
			expect(spy.callCount).to.equal(5);
		});
	});

	describe('unstable_now', () => {
		it('should return number', () => {
			const res = unstable_now();
			expect(res).is.a('number');
			expect(res > 0).to.equal(true);
		});
	});
});