Back to Repositories

Testing Color Normalization Implementation in uni-app

This test suite validates the color normalization functionality in uni-app’s nvue styler component. It thoroughly examines the handling of various color formats including hex codes, RGB/RGBA values, and named colors, ensuring consistent color processing across the application.

Test Coverage Overview

The test suite provides comprehensive coverage of color normalization scenarios.

Key areas tested include:
  • 6-digit and 3-digit hex color codes
  • 8-digit hex codes with alpha channels
  • RGB and RGBA color formats
  • Named colors and special values like ‘transparent’
  • Invalid color value handling

Implementation Analysis

The testing approach uses Jest’s expect assertions to verify color format transformations. Each test case validates the normalizeColor function’s output against expected color values and formats.

The implementation employs pattern matching and format validation to ensure color values are properly normalized while maintaining alpha channel information where applicable.

Technical Details

Testing infrastructure includes:
  • Jest testing framework
  • TypeScript for type-safe testing
  • Custom color normalization function
  • Expect matchers for value comparison
  • Function reason validation for error cases

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Comprehensive edge case coverage
  • Consistent test structure and organization
  • Clear input/output validation
  • Error case handling verification
  • Type-safe testing approaches

dcloudio/uni-app

packages/uni-nvue-styler/__tests__/src_normalize_color.spec.ts

            
import { normalizeColor } from '../src/normalize/color'

describe('normalizeColor', () => {
  test('normalizeColor', () => {
    expect(normalizeColor('#000000', {})).toEqual({
      value: '#000000',
    })

    expect(normalizeColor('#000', {})).toEqual({
      value: '#000000',
      reason: expect.any(Function),
    })

    expect(normalizeColor('#f008', {})).toEqual({
      value: '#ff000088',
      reason: expect.any(Function),
    })

    expect(normalizeColor('#aaffffaa', {})).toEqual({
      value: '#aaffffaa',
    })

    expect(normalizeColor('#AAFFFFAA', {})).toEqual({
      value: '#AAFFFFAA',
    })

    expect(normalizeColor('rgb(0,0,0)', {})).toEqual({
      value: 'rgb(0,0,0)',
    })

    expect(normalizeColor('rgb(266,266,266)', {})).toEqual({
      value: null,
      reason: expect.any(Function),
    })
    expect(normalizeColor('rgba(0,0,0,1)', {})).toEqual({
      value: 'rgba(0,0,0,1)',
    })

    // blue
    expect(normalizeColor('blue', {})).toEqual({
      value: '#0000FF',
      reason: expect.any(Function),
    })

    expect(normalizeColor('transparent', {})).toEqual({
      value: 'rgba(0,0,0,0)',
    })
  })
})