Back to Repositories

Validating Japanese Locale Relative Time Formatting in dayjs

This test suite validates the Japanese (ja) locale implementation in Day.js, specifically focusing on relative time formatting. It ensures accurate translation and formatting of time differences in both past and future contexts.

Test Coverage Overview

The test suite comprehensively covers relative time formatting in Japanese locale.

Key areas tested include:
  • Past and future time expressions
  • Multiple time units (days, minutes, hours, months, years)
  • Various time intervals
  • Comparison with moment.js implementation

Implementation Analysis

The testing approach utilizes Jest’s testing framework with MockDate for consistent date handling. The implementation compares Day.js output with moment.js to ensure compatibility and correct Japanese language formatting.

Testing patterns include:
  • Array-driven test cases
  • Direct comparison with moment.js reference implementation
  • Boolean parameter testing for fromNow() method

Technical Details

Testing tools and configuration:
  • Jest as the testing framework
  • MockDate for date manipulation
  • Day.js relative time plugin
  • Japanese locale import
  • Moment.js for reference comparison

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Consistent test setup and teardown using beforeEach/afterEach
  • Systematic test case organization
  • Cross-library validation
  • Comprehensive edge case coverage
  • Clean and maintainable test structure

iamkun/dayjs

test/locale/ja.test.js

            
import MockDate from 'mockdate'
import moment from 'moment'
import dayjs from '../../src'
import relativeTime from '../../src/plugin/relativeTime'
import '../../src/locale/ja'

dayjs.extend(relativeTime)

beforeEach(() => {
  MockDate.set(new Date())
})

afterEach(() => {
  MockDate.reset()
})

it('Finnish locale relative time in past and future', () => {
  const cases = [
    [1, 'd', '1日後'],
    [-1, 'd', '1日前'],
    [2, 'd', '2日後'],
    [-2, 'd', '2日前'],
    [10, 'd', '10日後'],
    [-10, 'd', '10日前'],
    [6, 'm', '6分後'],
    [-6, 'm', '6分前'],
    [5, 'h', '5時間後'],
    [-5, 'h', '5時間前'],
    [3, 'M', '3ヶ月後'],
    [-3, 'M', '3ヶ月前'],
    [4, 'y', '4年後'],
    [-4, 'y', '4年前']
  ]
  cases.forEach((c) => {
    expect(dayjs().add(c[0], c[1]).locale('ja').fromNow())
      .toBe(c[2])
    expect(dayjs().add(c[0], c[1]).locale('ja').fromNow())
      .toBe(moment().add(c[0], c[1]).locale('ja').fromNow())
  })
  expect(dayjs().add(-10, 'd').locale('ja').fromNow(true))
    .toBe('10日')
  expect(dayjs().add(-10, 'd').locale('ja').fromNow(true))
    .toBe(moment().add(-10, 'd').locale('ja').fromNow(true))
})