Back to Repositories

Testing Time Formatting Utilities Implementation in Canal

This test suite validates the formatTime utility function in Canal’s admin UI, focusing on timestamp formatting and relative time calculations. It ensures proper handling of various time formats and localization requirements for the Chinese interface.

Test Coverage Overview

The test suite provides comprehensive coverage of the formatTime utility function.

Key areas tested include:
  • Unix timestamp conversion
  • Relative time calculations (just now, minutes ago, hours ago)
  • Custom date format patterns
  • Chinese localization handling
  • Edge cases for different time intervals

Implementation Analysis

The testing approach utilizes Jest’s describe/it pattern for structured test organization. Each test case focuses on a specific time formatting scenario, using fixed timestamps and dynamic current time calculations.

The implementation leverages Jest’s expect assertions with toBe matchers for precise string comparison, ensuring accurate formatting results.

Technical Details

Testing infrastructure includes:
  • Jest testing framework
  • ES6 module import/export syntax
  • Date object manipulation
  • Fixed timestamp (2018-07-13 17:54:01) for consistent testing
  • Dynamic time calculations using Date.now()
  • Custom format string parsing

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Isolated test cases with clear purpose
  • Consistent test naming convention
  • Coverage of both fixed and relative time scenarios
  • Proper handling of time-sensitive operations
  • Comprehensive format string testing
  • Localization consideration in assertions

alibaba/canal

admin/admin-ui/tests/unit/utils/formatTime.spec.js

            
import { formatTime } from '@/utils/index.js'

describe('Utils:formatTime', () => {
  const d = new Date('2018-07-13 17:54:01') // "2018-07-13 17:54:01"
  const retrofit = 5 * 1000

  it('ten digits timestamp', () => {
    expect(formatTime((d / 1000).toFixed(0))).toBe('7月13日17时54分')
  })
  it('test now', () => {
    expect(formatTime(+new Date() - 1)).toBe('刚刚')
  })
  it('less two minute', () => {
    expect(formatTime(+new Date() - 60 * 2 * 1000 + retrofit)).toBe('2分钟前')
  })
  it('less two hour', () => {
    expect(formatTime(+new Date() - 60 * 60 * 2 * 1000 + retrofit)).toBe('2小时前')
  })
  it('less one day', () => {
    expect(formatTime(+new Date() - 60 * 60 * 24 * 1 * 1000)).toBe('1天前')
  })
  it('more than one day', () => {
    expect(formatTime(d)).toBe('7月13日17时54分')
  })
  it('format', () => {
    expect(formatTime(d, '{y}-{m}-{d} {h}:{i}')).toBe('2018-07-13 17:54')
    expect(formatTime(d, '{y}-{m}-{d}')).toBe('2018-07-13')
    expect(formatTime(d, '{y}/{m}/{d} {h}-{i}')).toBe('2018/07/13 17-54')
  })
})