Back to Repositories

Testing Preprocessor Range Detection in uni-app

This test suite validates the preprocessing functionality in uni-app, specifically focusing on conditional code inclusion based on preprocessor directives. It tests the isInPreprocessor method which determines if a given code position falls within preprocessor blocks.

Test Coverage Overview

The test suite provides comprehensive coverage of the preprocessor’s range detection capabilities.

Key areas tested include:
  • Nested preprocessor directive handling (#ifdef blocks)
  • Position-based preprocessor detection
  • Context-aware preprocessing with conditional flags
  • Multiple preprocessor block interactions

Implementation Analysis

The testing approach uses Jest’s snapshot testing to verify the preprocessing behavior across different code positions. It implements a systematic position-by-position validation pattern, checking preprocessor boundary detection for CSS-like code blocks with nested conditional directives.

The test leverages TypeScript’s type system for result validation with tuple arrays containing position, character, and preprocessor state information.

Technical Details

Testing tools and configuration:
  • Jest as the primary testing framework
  • TypeScript for type-safe test implementation
  • Snapshot testing for output verification
  • Custom preprocess utility with context configuration
  • Array-based result collection for position tracking

Best Practices Demonstrated

The test exhibits several testing best practices including isolated test cases, clear input/output scenarios, and comprehensive state validation.

Notable practices include:
  • Systematic position-based testing approach
  • Strong typing for test results
  • Snapshot testing for complex output validation
  • Clear test case organization and setup

dcloudio/uni-app

packages/uni-preprocess/__tests__/range.spec.ts

            
// import { writeFileSync } from 'node:fs'
// import { resolve } from 'node:path'
import { preprocess } from '../src/index'

describe('preprocess', () => {
  test('isInPreprocessor', () => {
    const code = `
.test {
    color:red
}
// #ifdef B
.test {
    color:blue
}
// #ifdef B1
.test {
    color:yellow
}
// #endif
.test {
    color:black
}
// #endif
.test {
    color:green
}
    `
    const { isInPreprocessor } = preprocess(code, {
      context: { B: true },
    })
    const result: [number, string, boolean][] = []
    for (let i = 0; i < code.length; i++) {
      result.push([i, code[i], isInPreprocessor(i)])
    }
    expect(result).toMatchSnapshot()
  })
})