Back to Repositories

Testing Context API Implementation in Preact

This test suite validates the createContext API implementation in Preact, focusing on the core context creation functionality and provider component behavior. The tests ensure proper context object structure and verify the Provider component’s handling of props and children.

Test Coverage Overview

The test suite covers essential aspects of the createContext functionality in Preact.

Key areas tested include:
  • Context object structure verification
  • Provider component property validation
  • Children rendering capabilities
  • Value propagation through context
The tests focus on core functionality while handling basic use cases of context creation and provider implementation.

Implementation Analysis

The testing approach utilizes Jest and Chai assertion library to validate the context API implementation. The tests employ JSX syntax with createElement for component creation and leverage describe/it blocks for organized test structure.

The implementation demonstrates proper isolation of test cases and clear separation of Provider and Consumer testing concerns.

Technical Details

Testing tools and configuration:
  • Jest as the test runner
  • Chai for assertions
  • JSX transformation with createElement
  • ESLint configuration for browser and mocha environments
  • Import statements showing proper module organization

Best Practices Demonstrated

The test suite exemplifies several testing best practices including clear test case isolation, meaningful test descriptions, and proper assertion patterns.

Notable practices include:
  • Granular test case organization
  • Clear test naming conventions
  • Proper setup of test environment
  • Focused component property validation

preactjs/preact

test/shared/createContext.test.js

            
import { createElement, createContext } from '../../';
import { expect } from 'chai';

/** @jsx createElement */
/* eslint-env browser, mocha */

describe('createContext', () => {
	it('should return a Provider and a Consumer', () => {
		const context = createContext();
		expect(context).to.have.property('Provider');
		expect(context).to.have.property('Consumer');
	});

	it('should return a valid Provider Component', () => {
		const { Provider } = createContext();
		const contextValue = { value: 'test' };
		const children = [<div>child1</div>, <div>child2</div>];

		const providerComponent = <Provider {...contextValue}>{children}</Provider>;
		//expect(providerComponent).to.have.property('tag', 'Provider');
		expect(providerComponent.props.value).to.equal(contextValue.value);
		expect(providerComponent.props.children).to.equal(children);
	});
});