Back to Repositories

Testing Component Unmounting Behavior in PreactJS

This test suite validates the unmountComponentAtNode functionality in Preact’s React compatibility layer. It ensures proper component unmounting behavior and cleanup of DOM elements through comprehensive unit tests.

Test Coverage Overview

The test suite covers critical unmounting scenarios for Preact components.

Key areas tested include:
  • Successful unmounting of mounted components
  • Handling of unmounting attempts on empty nodes
  • Verification of DOM cleanup after unmounting
  • Edge case handling for non-mounted components

Implementation Analysis

The testing approach utilizes Jest’s describe/it pattern with setup and teardown hooks for consistent test environments. The implementation leverages Preact’s React compatibility layer to ensure proper unmounting behavior that matches React’s expectations.

Technical patterns include:
  • Component mounting and unmounting lifecycle verification
  • DOM state validation
  • Return value assertion for unmounting operations

Technical Details

Testing infrastructure includes:
  • Jest test framework
  • Preact/compat package for React compatibility
  • Custom helper utilities for scratch element setup
  • Assertion library for expectations verification
  • BeforeEach/AfterEach hooks for test isolation

Best Practices Demonstrated

The test suite exemplifies high-quality testing practices through isolated test cases and proper setup/teardown patterns.

Notable practices include:
  • Clean test environment between runs
  • Explicit test case descriptions
  • Comprehensive assertion coverage
  • Proper resource cleanup
  • Consistent testing patterns across cases

preactjs/preact

compat/test/browser/unmountComponentAtNode.test.js

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

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

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

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

	it('should unmount a root node', () => {
		const App = () => <div>foo</div>;
		React.render(<App />, scratch);

		expect(unmountComponentAtNode(scratch)).to.equal(true);
		expect(scratch.innerHTML).to.equal('');
	});

	it('should do nothing if root is not mounted', () => {
		expect(unmountComponentAtNode(scratch)).to.equal(false);
		expect(scratch.innerHTML).to.equal('');
	});
});