Back to Repositories

Validating Hydration Compatibility Layer in PreactJS

This test suite validates the hydration functionality in Preact’s compatibility layer, focusing on React-style JSX rendering and callback handling. The tests ensure proper DOM element preservation and event handling during hydration.

Test Coverage Overview

The test suite covers critical hydration scenarios in Preact’s React compatibility layer.

Key areas tested include:
  • Preservation of DOM element focus states during hydration
  • Proper handling of React-style JSX rendering
  • Callback execution verification during hydration
  • DOM element state maintenance

Implementation Analysis

The testing approach utilizes Jest’s describe/it pattern combined with custom test utilities for DOM manipulation. The implementation leverages Preact’s hydrate function from the compat layer, validating both synchronous rendering and callback behaviors.

Technical patterns include:
  • DOM element focus state verification
  • Spy function usage for callback testing
  • Scratch element setup and teardown

Technical Details

Testing infrastructure includes:
  • Jest test framework
  • Sinon for spy functions
  • Custom helper utilities (setupScratch, teardown)
  • DOM manipulation APIs
  • Preact/compat hydrate function

Best Practices Demonstrated

The test suite exemplifies strong testing practices through proper test isolation and cleanup. Each test case maintains independence through beforeEach/afterEach hooks, ensuring a clean test environment.

Notable practices include:
  • Consistent setup and teardown procedures
  • Focused test cases with clear assertions
  • Proper DOM cleanup between tests
  • Effective use of spy functions for behavior verification

preactjs/preact

compat/test/browser/hydrate.test.js

            
import React, { hydrate } from 'preact/compat';
import { setupScratch, teardown } from '../../../test/_util/helpers';

describe('compat hydrate', () => {
	/** @type {HTMLDivElement} */
	let scratch;

	beforeEach(() => {
		scratch = setupScratch();
	});

	afterEach(() => {
		teardown(scratch);
	});

	it('should render react-style jsx', () => {
		const input = document.createElement('input');
		scratch.appendChild(input);
		input.focus();
		expect(document.activeElement).to.equalNode(input);

		hydrate(<input />, scratch);
		expect(document.activeElement).to.equalNode(input);
	});

	it('should call the callback', () => {
		scratch.innerHTML = '<div></div>';

		let spy = sinon.spy();
		hydrate(<div />, scratch, spy);
		expect(spy).to.be.calledOnce;
		expect(spy).to.be.calledWithExactly();
	});
});