-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathformatting.unit.test.ts
More file actions
341 lines (300 loc) · 9.38 KB
/
formatting.unit.test.ts
File metadata and controls
341 lines (300 loc) · 9.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import ansis from 'ansis';
import {
formatBytes,
formatCoveragePercentage,
formatDate,
formatDuration,
indentLines,
pluginMetaLogFormatter,
pluralize,
pluralizeToken,
roundDecimals,
serializeCommandWithArgs,
singleQuote,
slugify,
transformLines,
truncateMultilineText,
truncateText,
} from './formatting.js';
describe('roundDecimals', () => {
it('should remove extra decimals', () => {
expect(roundDecimals(1.2345, 2)).toBe(1.23);
});
it('should round last decimal', () => {
expect(roundDecimals(123.456, 2)).toBe(123.46);
});
it('should return number to prevent unnecessary trailing 0s in decimals', () => {
const result = roundDecimals(42.500_001, 3);
expect(result).toBeTypeOf('number');
expect(result.toString()).toBe('42.5');
expect(result.toString()).not.toBe('42.50');
});
it('should leave integers unchanged', () => {
const value = 42;
const result = roundDecimals(value, 3);
expect(result).toBe(value);
expect(result.toString()).toBe('42');
});
it('should round to integer if max decimals set to 0', () => {
expect(roundDecimals(100.5, 0)).toBe(101);
});
});
describe('slugify', () => {
it.each([
['Largest Contentful Paint', 'largest-contentful-paint'],
['cumulative-layout-shift', 'cumulative-layout-shift'],
['max-lines-200', 'max-lines-200'],
['rxjs/finnish', 'rxjs-finnish'],
['@typescript-eslint/no-explicit-any', 'typescript-eslint-no-explicit-any'],
['Code PushUp ', 'code-pushup'],
])('should transform "%s" to valid slug "%s"', (text, slug) => {
expect(slugify(text)).toBe(slug);
});
});
describe('pluralize', () => {
it.each([
['warning', 'warnings'],
['error', 'errors'],
['category', 'categories'],
['status', 'statuses'],
['branch', 'branches'],
])('should pluralize "%s" as "%s"', (singular, plural) => {
expect(pluralize(singular)).toBe(plural);
});
it('should not pluralize if 1 passed in as amount', () => {
expect(pluralize('audit', 1)).toBe('audit');
});
it('should pluralize if amount is other than 1/-1', () => {
expect(pluralize('audit', 2)).toBe('audits');
});
});
describe('formatBytes', () => {
it.each([
[0, '0 B'],
[-1, '0 B'],
[1000, '1000 B'],
[10_000, '9.77 kB'],
[10_000_000, '9.54 MB'],
[10_000_000_000, '9.31 GB'],
[10_000_000_000_000, '9.09 TB'],
[5_000_000_000_000_000, '4.44 PB'],
])('should log file sizes correctly for %s', (bytes, displayValue) => {
expect(formatBytes(bytes)).toBe(displayValue);
});
it('should log file sizes correctly with correct decimal', () => {
expect(formatBytes(10_000, 1)).toBe('9.8 kB');
});
});
describe('pluralizeToken', () => {
it.each([
[-2, '-2 files'],
[-1, '-1 file'],
[0, '0 files'],
[1, '1 file'],
[2, '2 files'],
])('should log correct plural for %s', (times, plural) => {
expect(pluralizeToken('file', times)).toBe(plural);
});
});
describe('formatDuration', () => {
it.each([
[-1, '-1 ms'],
[0, '0 ms'],
[23, '23 ms'],
[891, '891 ms'],
[499.85, '500 ms'],
[1200, '1.2 s'],
[56_789, '56.79 s'],
[60_000, '60 s'],
])('should format duration of %s milliseconds as %s', (ms, displayValue) => {
expect(formatDuration(ms)).toBe(displayValue);
});
});
describe('formatDate', () => {
it('should produce human-readable date and time in English', () => {
expect(formatDate(new Date('2024-01-23T09:50:09.606Z'))).toBe(
'Tue, Jan 23, 2024, 9:50 AM UTC',
);
});
// see https://github.com/nodejs/node/issues/45171
it('should not include narrow non-breaking space', () => {
expect(formatDate(new Date())).not.toMatch(' ');
});
});
describe('truncateText', () => {
it('should replace overflowing text with ellipsis at the end', () => {
expect(truncateText('All work and no play makes Jack a dull boy', 32)).toBe(
'All work and no play makes Jack…',
);
});
it('should leave text unchanged when within character limit passed as number', () => {
expect(truncateText("Here's Johnny!", 32)).toBe("Here's Johnny!");
});
it('should produce truncated text which fits within limit passed as number', () => {
expect(
truncateText('All work and no play makes Jack a dull boy', 32).length,
).toBeLessThanOrEqual(32);
});
it('should leave text unchanged when within character limit passed as options', () => {
expect(truncateText("Here's Johnny!", { maxChars: 32 })).toBe(
"Here's Johnny!",
);
});
it('should produce truncated text with ellipsis at the start', () => {
expect(
truncateText('Yesterday cloudy day.', {
maxChars: 10,
position: 'start',
}),
).toBe('…oudy day.');
});
it('should produce truncated text with ellipsis at the middle', () => {
expect(
truncateText('Horrendous amounts of lint issues are present Tony!', {
maxChars: 8,
position: 'middle',
}),
).toBe('Hor…ny!');
});
it('should produce truncated text with ellipsis at the end', () => {
expect(truncateText("I'm Johnny!", { maxChars: 10, position: 'end' })).toBe(
"I'm Johnn…",
);
});
it('should produce truncated text with custom ellipsis', () => {
expect(truncateText("I'm Johnny!", { maxChars: 10, ellipsis: '...' })).toBe(
"I'm Joh...",
);
});
});
describe('transformMultilineText', () => {
it('should replace additional lines with an ellipsis', () => {
const error = `SchemaValidationError: Invalid CoreConfig in code-pushup.config.ts file
✖ Invalid input: expected array, received undefined
→ at plugins`;
expect(truncateMultilineText(error)).toBe(
'SchemaValidationError: Invalid CoreConfig in code-pushup.config.ts file […]',
);
});
it('should leave one-liner texts unchanged', () => {
expect(truncateMultilineText('Hello, world!')).toBe('Hello, world!');
});
it('should omit ellipsis if additional lines have no non-whitespace characters', () => {
expect(truncateMultilineText('- item 1\n \n\n')).toBe('- item 1');
});
});
describe('transformLines', () => {
it('should apply custom transformation to each line', () => {
let count = 0;
expect(
transformLines(
`export function greet(name = 'World') {\n console.log('Hello, ' + name + '!');\n}\n`,
line => {
const prefix = `${++count} | `;
return `${ansis.gray(prefix)}${line}`;
},
),
).toBe(
`
${ansis.gray('1 | ')}export function greet(name = 'World') {
${ansis.gray('2 | ')} console.log('Hello, ' + name + '!');
${ansis.gray('3 | ')}}
${ansis.gray('4 | ')}`.trimStart(),
);
});
it('should support CRLF line endings', () => {
expect(
transformLines(
'ESLint v9.16.0\r\n\r\nAll files pass linting.\r\n',
line => `> ${line}`,
),
).toBe(
`
> ESLint v9.16.0
>
> All files pass linting.
> `.trimStart(),
);
});
});
describe('indentLines', () => {
it('should indent each line by given number of spaces', () => {
expect(indentLines('ESLint v9.16.0\n\nAll files pass linting.\n', 2)).toBe(
`
ESLint v9.16.0
All files pass linting.
`.slice(1), // ignore first line break
);
});
});
describe('serializeCommandWithArgs', () => {
it('should serialize command and args into an equivalent shell string', () => {
expect(
serializeCommandWithArgs({
command: 'npx',
args: ['eslint', '.', '--format=json'],
}),
).toBe('npx eslint . --format=json');
});
it('should omit args if missing', () => {
expect(serializeCommandWithArgs({ command: 'ls' })).toBe('ls');
});
});
describe('pluginMetaLogFormatter', () => {
it('should prefix plugin title', () => {
expect(pluginMetaLogFormatter('ESLint')('Found 42 rules in total')).toBe(
`${ansis.blue('[ESLint]')} Found 42 rules in total`,
);
});
it('should align multiline message with prefix', () => {
expect(
ansis.strip(
pluginMetaLogFormatter('Coverage')(
'Created 3 groups:\n- Line coverage\n- Branch coverage\n- Function coverage',
),
),
).toBe(
`
[Coverage] Created 3 groups:
- Line coverage
- Branch coverage
- Function coverage
`.trim(),
);
});
});
describe('formatCoveragePercentage', () => {
it('should render percentage', () => {
expect(formatCoveragePercentage({ covered: 125, total: 1000 })).toBe(
'12.5%',
);
});
it('should render max 1 decimal', () => {
expect(formatCoveragePercentage({ covered: 1, total: 3 })).toBe('33.3%');
});
it('should render at least 1 decimal', () => {
expect(formatCoveragePercentage({ covered: 0, total: 10 })).toBe('0.0%');
});
it('should round decimal up if appropriate', () => {
expect(formatCoveragePercentage({ covered: 2, total: 3 })).toBe('66.7%');
});
it('should not render invalid percentage', () => {
expect(formatCoveragePercentage({ covered: 0, total: 0 })).toBe('-');
});
});
describe('singleQuote', () => {
it.each([
['hello', "'hello'"],
["it's", String.raw`'it\'s'`],
[String.raw`back\slash`, String.raw`'back\\slash'`],
['line\nbreak', String.raw`'line\nbreak'`],
])(
'should escape %j for use in a single-quoted JS literal',
(input, expected) => {
expect(singleQuote(input)).toBe(expected);
},
);
it('should leave double quotes unescaped', () => {
expect(singleQuote('say "hi"')).toBe(`'say "hi"'`);
});
});