Back to Repositories

Testing Date Comparison Methods Implementation in dayjs

This test suite validates the date comparison functionality in Day.js, focusing on isBefore, isAfter, and isSame methods. The tests ensure accurate date comparisons between Day.js objects and various input formats.

Test Coverage Overview

The test suite provides comprehensive coverage of Day.js date comparison methods.

  • Tests isBefore, isAfter, and isSame comparisons between Day.js objects
  • Validates comparison behavior with no parameters
  • Verifies string date format comparisons
  • Includes edge cases for different date formats

Implementation Analysis

The testing approach utilizes Jest’s describe/it pattern for organized test grouping. MockDate is employed to ensure consistent date-based testing.

Key patterns include:
  • Clone-based object manipulation for controlled testing
  • Explicit boolean assertions using toBe
  • Systematic test organization for each comparison method

Technical Details

Testing infrastructure includes:

  • Jest testing framework
  • MockDate for date manipulation
  • beforeEach/afterEach hooks for test isolation
  • Day.js core library integration

Best Practices Demonstrated

The test suite exemplifies high-quality testing practices through clear organization and thorough coverage.

  • Proper test isolation using MockDate
  • Consistent test setup and teardown
  • Comprehensive method coverage
  • Clear test case descriptions

iamkun/dayjs

test/query.test.js

            
import MockDate from 'mockdate'
import dayjs from '../src'

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

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


describe('Is Before Is After Is Same', () => {
  it('Compare to dayjs object', () => {
    const dayA = dayjs()
    const dayB = dayA.clone().add(1, 'day')
    const dayC = dayA.clone().subtract(1, 'day')
    expect(dayC.isBefore(dayA)).toBe(true)
    expect(dayA.isSame(dayjs())).toBe(true)
    expect(dayB.isAfter(dayA)).toBe(true)
    expect(dayA.isSame()).toBe(true)
    expect(dayB.isAfter()).toBe(true)
    expect(dayC.isBefore()).toBe(true)
  })

  it('No value', () => {
    const dayA = dayjs()
    const dayB = dayA.clone().add(1, 'day')
    const dayC = dayA.clone().subtract(1, 'day')
    expect(dayA.isSame()).toBe(true)
    expect(dayB.isAfter()).toBe(true)
    expect(dayC.isBefore()).toBe(true)
  })

  it('With string', () => {
    const dayD = dayjs()
    expect(dayD.isSame('20180101')).toBe(false)
    expect(dayD.isAfter('20180101')).toBe(true)
    expect(dayD.isBefore('20180101')).toBe(false)
  })
})