Back to Repositories

Testing Memo Component Detection in Preact

This test suite evaluates the isMemo utility function in Preact’s compatibility layer, which determines if a component is wrapped with React.memo(). The tests verify correct detection of memoized components and proper handling of various input types.

Test Coverage Overview

The test suite provides comprehensive coverage of the isMemo functionality, testing both valid and invalid use cases.

  • Validates behavior with invalid arguments (null, primitives, objects)
  • Tests detection of genuine memoized Preact components
  • Verifies non-memoized components return false
  • Checks behavior with Preact and compat vnodes

Implementation Analysis

The testing approach employs Jest’s describe/it pattern to organize test cases logically. Each test case focuses on a specific aspect of isMemo functionality, using both Preact’s native createElement and the compat layer’s implementation.

  • Uses expect().to.equal() assertions for boolean checks
  • Implements JSX syntax for component creation
  • Leverages Preact’s memo HOC for component memoization

Technical Details

  • Testing Framework: Jest
  • Component Library: Preact
  • Key Imports: createElement, Fragment from Preact core
  • Compat Layer: preact/compat for React compatibility
  • Assertion Style: Chai-like expect syntax

Best Practices Demonstrated

The test suite exemplifies several testing best practices for component utilities.

  • Comprehensive edge case coverage
  • Clear test case isolation
  • Consistent assertion patterns
  • Proper setup of test environment
  • Effective use of describe blocks for organization

preactjs/preact

compat/test/browser/isMemo.test.js

            
import { createElement as preactCreateElement, Fragment } from 'preact';
import React, { createElement, isMemo, memo } from 'preact/compat';

describe('isMemo', () => {
	it('should check return false for invalid arguments', () => {
		expect(isMemo(null)).to.equal(false);
		expect(isMemo(false)).to.equal(false);
		expect(isMemo(true)).to.equal(false);
		expect(isMemo('foo')).to.equal(false);
		expect(isMemo(123)).to.equal(false);
		expect(isMemo([])).to.equal(false);
		expect(isMemo({})).to.equal(false);
	});

	it('should detect a preact memo', () => {
		function Foo() {
			return <h1>Hello World</h1>;
		}
		let App = memo(Foo);
		expect(isMemo(App)).to.equal(true);
	});

	it('should not detect a normal element', () => {
		function Foo() {
			return <h1>Hello World</h1>;
		}
		expect(isMemo(Foo)).to.equal(false);
	});

	it('should detect a preact vnode as false', () => {
		expect(isMemo(preactCreateElement(Fragment, {}))).to.equal(false);
	});

	it('should detect a compat vnode as false', () => {
		expect(isMemo(React.createElement(Fragment, {}))).to.equal(false);
	});
});