Back to Repositories

Testing Select Component Multiple Selection Behavior in Preact

This test suite validates the functionality of the Select component in Preact’s compatibility layer, focusing on multiple selection behavior and value handling. It ensures proper rendering and state management of select elements with multiple options.

Test Coverage Overview

The test suite covers critical functionality of the Select component, specifically focusing on multiple selection capabilities.

  • Validates correct handling of multiple selected values passed as an array
  • Verifies proper selection state of individual options
  • Tests value property synchronization
  • Ensures compatibility with React’s select implementation

Implementation Analysis

The testing approach utilizes Jest’s describe/it pattern with Preact’s compat layer to ensure React compatibility. The implementation leverages custom test utilities for DOM manipulation and cleanup.

Key patterns include:
  • Component rendering with specific prop configurations
  • DOM state verification using property checks
  • Cleanup routines to prevent test pollution

Technical Details

Testing infrastructure includes:

  • Jest as the testing framework
  • Custom setupScratch and teardown utilities
  • Preact/compat for React compatibility layer
  • DOM manipulation and assertion utilities

Best Practices Demonstrated

The test suite exemplifies several testing best practices in component validation.

  • Proper test isolation through beforeEach/afterEach hooks
  • Clear test case descriptions
  • Specific assertions targeting component behavior
  • Efficient setup and teardown procedures

preactjs/preact

compat/test/browser/select.test.js

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

describe('Select', () => {
	let scratch;

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

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

	it('should work with multiple selected (array of values)', () => {
		function App() {
			return (
				<select multiple value={['B', 'C']}>
					<option value="A">A</option>
					<option value="B">B</option>
					<option value="C">C</option>
				</select>
			);
		}

		render(<App />, scratch);
		const options = scratch.firstChild.children;
		expect(options[0]).to.have.property('selected', false);
		expect(options[1]).to.have.property('selected', true);
		expect(options[2]).to.have.property('selected', true);
		expect(scratch.firstChild.value).to.equal('B');
	});
});