Back to Repositories

Testing Table of Contents Generation in 30-seconds-of-code

This test suite evaluates the TocReader utility’s ability to generate table of contents from HTML content. It validates the parsing of hierarchical heading structures and proper generation of nested ordered lists with anchor links.

Test Coverage Overview

The test suite provides comprehensive coverage of the TocReader.readToC functionality.

  • Tests successful ToC generation from H2-H4 headings
  • Verifies proper nesting of ordered lists
  • Handles empty input scenarios
  • Validates anchor link preservation

Implementation Analysis

The testing approach utilizes Jest’s describe/it pattern for structured test organization. Tests employ string-based HTML input fixtures and explicit output validation.

  • Uses vitest testing framework
  • Implements expect().toBe() assertions
  • Employs template literals for test data

Technical Details

  • Testing Framework: Vitest
  • Import Type: ES Modules
  • Test Structure: BDD style with describe/it blocks
  • Assertion Style: Jest-compatible expect statements
  • Test Data: Inline HTML string templates

Best Practices Demonstrated

The test suite exemplifies clean testing practices with clear test case isolation and explicit expectations.

  • Descriptive test case naming
  • Isolated test scenarios
  • Clear input/output relationships
  • Edge case handling
  • Readable HTML fixtures

chalarangelo/30-seconds-of-code

spec/lib/contentUtils/tocReader.test.js

            
import { describe, it, expect } from 'vitest';
import TocReader from '#src/lib/contentUtils/tocReader.js';

describe('TocReader.readToC', () => {
  it('should read and build a table of contents from HTML', () => {
    const html = `
      <h2><a id="foo" href="#foo">Foo</a></h2>
      <h3><a id="bar" href="#bar">Bar</a></h3>
      <h4><a id="baz" href="#baz">Baz</a></h4>
    `;

    const toc = TocReader.readToC(html);

    expect(toc).toBe(
      '<ol><li><a href="#foo">Foo</a><ol><li><a href="#bar">Bar</a><ol><li><a href="#baz">Baz</a></li></ol></li></ol></li></ol>'
    );
  });

  it('should return undefined if no headings are found', () => {
    const html = '';

    const toc = TocReader.readToC(html);

    expect(toc).toBe(undefined);
  });
});