Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/plugin/devHelper/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@ export default (o, c, d) => {
}
return oldLocale(preset, object, isLocal)
}

const oldDiff = proto.diff
proto.diff = function (date, unit, float) {
const isInvalidDate = !date || !d(date).isValid()
if (isInvalidDate) {
console.warn('Invalid usage: diff() requires a valid comparison date as the first argument. https://day.js.org/docs/en/display/difference')
}

return oldDiff.call(this, date, unit, float)
}
}
}

45 changes: 45 additions & 0 deletions test/plugin/devHelper.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import MockDate from 'mockdate'
import dayjs from '../../src'
import customParseFormat from '../../src/plugin/customParseFormat'
import devHelper from '../../src/plugin/devHelper'
import localeData from '../../src/plugin/localeData'

dayjs.extend(devHelper)

Expand Down Expand Up @@ -38,3 +40,46 @@ it('Warning: Setting locale before loading locale', () => {
dayjs.locale('zh-cn')
expect(consoleSpy).toHaveBeenCalledWith('Guessing you may want to use locale zh-cn, you have to load it before using it. https://day.js.org/docs/en/i18n/loading-into-nodejs')
})

describe('dev-helper: diff() usage warnings', () => {
const diffWarningMsg = 'Invalid usage: diff() requires a valid comparison date as the first argument. https://day.js.org/docs/en/display/difference'

beforeAll(() => {
dayjs.extend(customParseFormat)
dayjs.extend(localeData)
})

beforeEach(() => {
jest.clearAllMocks()
})

it('warns when diff() is called with no comparison date', () => {
const consoleSpy = jest.spyOn(console, 'warn')
dayjs('2025-01-10').diff()
expect(consoleSpy).toHaveBeenCalledWith(diffWarningMsg)
})

it('warns when diff() is called with just the unit', () => {
const consoleSpy = jest.spyOn(console, 'warn')
dayjs('2025-01-10').diff('days')
expect(consoleSpy).toHaveBeenCalledWith(diffWarningMsg)
})

it('warns when diff() is called with an invalid comparison date (unparsable string)', () => {
const consoleSpy = jest.spyOn(console, 'warn')
dayjs('2025-01-10').diff('invalid-date', 'days')
expect(consoleSpy).toHaveBeenCalledWith(diffWarningMsg)
})

it('does NOT warn when diff() is called with a valid string date', () => {
const consoleSpy = jest.spyOn(console, 'warn')
dayjs('2025-01-10').diff('2025-01-09', 'days')
expect(consoleSpy).not.toHaveBeenCalledWith(diffWarningMsg)
})

it('does NOT warn when diff() is called with a valid Day.js instance', () => {
const consoleSpy = jest.spyOn(console, 'warn')
dayjs('2025-01-10').diff(dayjs(), 'days')
expect(consoleSpy).not.toHaveBeenCalledWith(diffWarningMsg)
})
})