Back to Repositories

Testing Custom Built-in Element Integration in Preact

This test suite evaluates the integration of customized built-in elements within Preact components. It verifies proper creation, rendering, and lifecycle behavior of custom elements that extend native HTML elements, ensuring compatibility between Preact’s virtual DOM and the Web Components specification.

Test Coverage Overview

The test suite provides comprehensive coverage of customized built-in elements functionality in Preact.

Key areas tested include:
  • Creation of custom elements extending HTMLDivElement
  • Proper rendering of components with ‘is’ attribute
  • Lifecycle callback execution verification
  • Integration between Preact components and native custom elements

Implementation Analysis

The testing approach utilizes Jest’s describe/it blocks with conditional execution based on browser support for custom elements. It implements a component-based test structure that combines Preact’s createElement and render methods with native Web Components APIs.

Notable patterns include:
  • Component class extension pattern
  • Spy-based callback verification
  • Custom element definition with extends option

Technical Details

Testing infrastructure includes:
  • Jest as the primary test runner
  • Sinon for spy functionality
  • Custom helper utilities (setupScratch, teardown)
  • DOM manipulation utilities
  • Web Components API integration

Best Practices Demonstrated

The test suite exemplifies high-quality testing practices through proper isolation and cleanup of test environments. Each test case maintains independence through beforeEach/afterEach hooks, implementing proper teardown procedures.

Notable practices include:
  • Isolated test environment setup
  • Proper cleanup after each test
  • Feature detection for browser compatibility
  • Clear separation of concerns between component and element definitions

preactjs/preact

test/browser/customBuiltInElements.test.js

            
import { createElement, render, Component } from 'preact';
import { setupScratch, teardown } from '../_util/helpers';

/** @jsx createElement */

const runSuite = typeof customElements == 'undefined' ? xdescribe : describe;

runSuite('customised built-in elements', () => {
	let scratch;

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

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

	it('should create built in elements correctly', () => {
		class Foo extends Component {
			render() {
				return <div is="built-in" />;
			}
		}

		const spy = sinon.spy();

		class BuiltIn extends HTMLDivElement {
			connectedCallback() {
				spy();
			}
		}

		customElements.define('built-in', BuiltIn, { extends: 'div' });

		render(<Foo />, scratch);

		expect(spy).to.have.been.calledOnce;
	});
});