-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathformatDate.test.ts
More file actions
79 lines (63 loc) · 2.38 KB
/
formatDate.test.ts
File metadata and controls
79 lines (63 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import i18next from 'i18next';
import { distanceInWordsToNow, formatDateToString } from './formatDate';
jest.mock('i18next', () => ({
t: jest.fn((key: string) => key.split('.')[1])
}));
jest.mock('../i18n', () => ({
// eslint-disable-next-line global-require
currentDateLocale: () => require('date-fns/locale').enUS
}));
describe('dateUtils', () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe('distanceInWordsToNow', () => {
it('returns "JustNow" for dates within 10 seconds', () => {
const now = new Date();
const recentDate = new Date(now.getTime() - 5000);
const result = distanceInWordsToNow(recentDate);
expect(i18next.t).toHaveBeenCalledWith('formatDate.JustNow');
expect(result).toBe('JustNow');
});
it('returns "15Seconds" for dates ~15s ago', () => {
const now = new Date();
const recentDate = new Date(now.getTime() - 15000);
const result = distanceInWordsToNow(recentDate);
expect(i18next.t).toHaveBeenCalledWith('formatDate.15Seconds');
expect(result).toBe('15Seconds');
});
it('returns formatted distance with "Ago" for dates over 46s', () => {
const now = new Date();
const oldDate = new Date(now.getTime() - 60000);
jest.mock('i18next', () => ({
t: jest.fn((key: string, { timeAgo }) => `${key}: ${timeAgo}`)
}));
const result = distanceInWordsToNow(oldDate);
expect(i18next.t).toHaveBeenCalledWith(
'formatDate.Ago',
expect.any(Object)
);
expect(result).toContain('Ago');
});
it('returns empty string for invalid date', () => {
const result = distanceInWordsToNow('not a date');
expect(result).toBe('');
});
});
describe('format', () => {
it('formats with time by default', () => {
const date = new Date('2025-07-16T12:34:56Z');
const formatted = formatDateToString(date);
expect(formatted).toMatch(/(\d{1,2}:\d{2})/); // Contains time
});
it('formats without time when showTime is false', () => {
const date = new Date('2025-07-16T12:34:56Z');
const formatted = formatDateToString(date, { showTime: false });
expect(formatted).not.toMatch(/(\d{1,2}:\d{2})/); // Contains time
});
it('returns empty string for invalid date', () => {
const formatted = formatDateToString('invalid date');
expect(formatted).toBe('');
});
});
});