-
Notifications
You must be signed in to change notification settings - Fork 26.1k
/
index.test.js
693 lines (575 loc) · 21.9 KB
/
index.test.js
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
import fs from 'fs-extra'
import os from 'os'
import execa from 'execa'
import { dirname, join } from 'path'
import findUp from 'next/dist/compiled/find-up'
import { nextBuild, nextLint } from 'next-test-utils'
const dirFirstTimeSetup = join(__dirname, '../first-time-setup')
const dirCustomConfig = join(__dirname, '../custom-config')
const dirWebVitalsConfig = join(__dirname, '../config-core-web-vitals')
const dirPluginRecommendedConfig = join(
__dirname,
'../plugin-recommended-config'
)
const dirPluginCoreWebVitalsConfig = join(
__dirname,
'../plugin-core-web-vitals-config'
)
const dirIgnoreDuringBuilds = join(__dirname, '../ignore-during-builds')
const dirCustomDirectories = join(__dirname, '../custom-directories')
const dirConfigInPackageJson = join(__dirname, '../config-in-package-json')
const dirInvalidOlderEslintVersion = join(
__dirname,
'../invalid-eslint-version'
)
const dirMaxWarnings = join(__dirname, '../max-warnings')
const dirEmptyDirectory = join(__dirname, '../empty-directory')
const dirEslintIgnore = join(__dirname, '../eslint-ignore')
const dirNoEslintPlugin = join(__dirname, '../no-eslint-plugin')
const dirNoConfig = join(__dirname, '../no-config')
const dirEslintCache = join(__dirname, '../eslint-cache')
const dirEslintCacheCustomDir = join(__dirname, '../eslint-cache-custom-dir')
const dirFileLinting = join(__dirname, '../file-linting')
describe('ESLint', () => {
describe('Next Build', () => {
test('first time setup', async () => {
const eslintrcJson = join(dirFirstTimeSetup, '.eslintrc.json')
await fs.writeFile(eslintrcJson, '')
const { stdout, stderr } = await nextBuild(dirFirstTimeSetup, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'No ESLint configuration detected. Run next lint to begin setup'
)
})
test('shows warnings and errors', async () => {
const { stdout, stderr } = await nextBuild(dirCustomConfig, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'Warning: External synchronous scripts are forbidden'
)
expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
})
test('ignore during builds', async () => {
const { stdout, stderr } = await nextBuild(dirIgnoreDuringBuilds, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).not.toContain('Failed to compile')
expect(output).not.toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
})
test('custom directories', async () => {
const { stdout, stderr } = await nextBuild(dirCustomDirectories, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain('Failed to compile')
expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
expect(output).toContain(
'Warning: External synchronous scripts are forbidden'
)
})
test('invalid older eslint version', async () => {
const { stdout, stderr } = await nextBuild(
dirInvalidOlderEslintVersion,
[],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain(
'Your project has an older version of ESLint installed'
)
})
test('empty directories do not fail the build', async () => {
const { stdout, stderr } = await nextBuild(dirEmptyDirectory, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).not.toContain('Build error occurred')
expect(output).not.toContain('NoFilesFoundError')
expect(output).toContain(
'Warning: External synchronous scripts are forbidden'
)
expect(output).toContain('Compiled successfully')
})
test('eslint ignored directories do not fail the build', async () => {
const { stdout, stderr } = await nextBuild(dirEslintIgnore, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).not.toContain('Build error occurred')
expect(output).not.toContain('AllFilesIgnoredError')
expect(output).toContain(
'Warning: External synchronous scripts are forbidden'
)
expect(output).toContain('Compiled successfully')
})
test('missing Next.js plugin', async () => {
const { stdout, stderr } = await nextBuild(dirNoEslintPlugin, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'The Next.js plugin was not detected in your ESLint configuration'
)
})
test('eslint caching is enabled', async () => {
const cacheDir = join(dirEslintCache, '.next', 'cache')
await fs.remove(cacheDir)
await nextBuild(dirEslintCache, [])
const files = await fs.readdir(join(cacheDir, 'eslint/'))
const cacheExists = files.some((f) => /\.cache/.test(f))
expect(cacheExists).toBe(true)
})
test('eslint cache lives in the user defined build directory', async () => {
const oldCacheDir = join(dirEslintCacheCustomDir, '.next', 'cache')
const newCacheDir = join(dirEslintCacheCustomDir, 'build', 'cache')
await fs.remove(oldCacheDir)
await fs.remove(newCacheDir)
await nextBuild(dirEslintCacheCustomDir, [])
expect(fs.existsSync(oldCacheDir)).toBe(false)
const files = await fs.readdir(join(newCacheDir, 'eslint/'))
const cacheExists = files.some((f) => /\.cache/.test(f))
expect(cacheExists).toBe(true)
})
})
describe('Next Lint', () => {
describe('First Time Setup ', () => {
async function nextLintTemp() {
const folder = join(
os.tmpdir(),
Math.random().toString(36).substring(2)
)
await fs.mkdirp(folder)
await fs.copy(dirNoConfig, folder)
try {
const nextDir = dirname(require.resolve('next/package'))
const nextBin = join(nextDir, 'dist/bin/next')
const { stdout } = await execa('node', [
nextBin,
'lint',
folder,
'--strict',
])
const pkgJson = JSON.parse(
await fs.readFile(join(folder, 'package.json'), 'utf8')
)
const eslintrcJson = JSON.parse(
await fs.readFile(join(folder, '.eslintrc.json'), 'utf8')
)
return { stdout, pkgJson, eslintrcJson }
} finally {
await fs.remove(folder)
}
}
test('show a prompt to set up ESLint if no configuration detected', async () => {
const eslintrcJson = join(dirFirstTimeSetup, '.eslintrc.json')
await fs.writeFile(eslintrcJson, '')
const { stdout, stderr } = await nextLint(dirFirstTimeSetup, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain('How would you like to configure ESLint?')
// Different options that can be selected
expect(output).toContain('Strict (recommended)')
expect(output).toContain('Base')
expect(output).toContain('Cancel')
})
test('installs eslint and eslint-config-next as devDependencies if missing', async () => {
const { stdout, pkgJson } = await nextLintTemp()
expect(stdout.replace(/(\r\n|\n|\r)/gm, '')).toContain(
'Installing devDependencies:- eslint- eslint-config-next'
)
expect(pkgJson.devDependencies).toHaveProperty('eslint')
expect(pkgJson.devDependencies).toHaveProperty('eslint-config-next')
})
test('creates .eslintrc.json file with a default configuration', async () => {
const { stdout, eslintrcJson } = await nextLintTemp()
expect(stdout).toContain(
'We created the .eslintrc.json file for you and included your selected configuration'
)
expect(eslintrcJson).toMatchObject({ extends: 'next/core-web-vitals' })
})
test('shows a successful message when completed', async () => {
const { stdout } = await nextLintTemp()
expect(stdout).toContain(
'ESLint has successfully been configured. Run next lint again to view warnings and errors'
)
})
})
test('shows warnings and errors', async () => {
const { stdout, stderr } = await nextLint(dirCustomConfig, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'Warning: External synchronous scripts are forbidden'
)
expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
})
test('shows warnings and errors with next/core-web-vitals config', async () => {
const { stdout, stderr } = await nextLint(dirWebVitalsConfig, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
"Warning: Do not use <img>. Use Image from 'next/image' instead."
)
expect(output).toContain(
'Error: External synchronous scripts are forbidden'
)
})
test('shows warnings and errors when extending plugin recommended config', async () => {
const { stdout, stderr } = await nextLint(
dirPluginRecommendedConfig,
[],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain(
'Warning: External synchronous scripts are forbidden'
)
expect(output).toContain(
'Error: next/document should not be imported outside of pages/_document.js.'
)
})
test('shows warnings and errors when extending plugin core-web-vitals config', async () => {
const { stdout, stderr } = await nextLint(
dirPluginCoreWebVitalsConfig,
[],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain(
"Warning: Do not use <img>. Use Image from 'next/image' instead."
)
expect(output).toContain(
'Error: External synchronous scripts are forbidden'
)
})
test('success message when no warnings or errors', async () => {
const eslintrcJson = join(dirFirstTimeSetup, '.eslintrc.json')
await fs.writeFile(eslintrcJson, '{ "extends": "next", "root": true }\n')
const { stdout, stderr } = await nextLint(dirFirstTimeSetup, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain('No ESLint warnings or errors')
})
test("don't create .eslintrc file if package.json has eslintConfig field", async () => {
const eslintrcFile =
(await findUp(
[
'.eslintrc.js',
'.eslintrc.cjs',
'.eslintrc.yaml',
'.eslintrc.yml',
'.eslintrc.json',
'.eslintrc',
],
{
cwd: '.',
}
)) ?? null
try {
// If we found a .eslintrc file, it's probably config from root Next.js directory. Rename it during the test
if (eslintrcFile) {
await fs.move(eslintrcFile, `${eslintrcFile}.original`)
}
const { stdout, stderr } = await nextLint(dirConfigInPackageJson, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).not.toContain(
'We created the .eslintrc file for you and included your selected configuration'
)
} finally {
// Restore original .eslintrc file
if (eslintrcFile) {
await fs.move(`${eslintrcFile}.original`, eslintrcFile)
}
}
})
test('quiet flag suppresses warnings and only reports errors', async () => {
const { stdout, stderr } = await nextLint(dirCustomConfig, ['--quiet'], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
expect(output).not.toContain(
'Warning: External synchronous scripts are forbidden'
)
})
test('custom directories', async () => {
const { stdout, stderr } = await nextLint(dirCustomDirectories, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output).toContain(
'Error: Comments inside children section of tag should be placed inside braces'
)
expect(output).toContain(
'Warning: External synchronous scripts are forbidden'
)
})
test('max warnings flag errors when warnings exceed threshold', async () => {
const { stdout, stderr } = await nextLint(
dirMaxWarnings,
['--max-warnings', 1],
{
stdout: true,
stderr: true,
}
)
expect(stderr).not.toEqual('')
expect(stderr).toContain(
'Warning: External synchronous scripts are forbidden'
)
expect(stdout).not.toContain(
'Warning: External synchronous scripts are forbidden'
)
})
test('max warnings flag does not error when warnings do not exceed threshold', async () => {
const { stdout, stderr } = await nextLint(
dirMaxWarnings,
['--max-warnings', 2],
{
stdout: true,
stderr: true,
}
)
expect(stderr).toEqual('')
expect(stderr).not.toContain(
'Warning: External synchronous scripts are forbidden'
)
expect(stdout).toContain(
'Warning: External synchronous scripts are forbidden'
)
})
test('format flag supports additional user-defined formats', async () => {
const { stdout, stderr } = await nextLint(
dirMaxWarnings,
['-f', 'codeframe'],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain(
'warning: External synchronous scripts are forbidden'
)
expect(stdout).toContain('<script src="https://example.com" />')
expect(stdout).toContain('2 warnings found')
})
test('eslint caching is enabled by default', async () => {
const cacheDir = join(dirEslintCache, '.next', 'cache')
await fs.remove(cacheDir)
await nextLint(dirEslintCache, [])
const files = await fs.readdir(join(cacheDir, 'eslint/'))
const cacheExists = files.some((f) => /\.cache/.test(f))
expect(cacheExists).toBe(true)
})
test('eslint caching is disabled with the --no-cache flag', async () => {
const cacheDir = join(dirEslintCache, '.next', 'cache')
await fs.remove(cacheDir)
await nextLint(dirEslintCache, ['--no-cache'])
expect(fs.existsSync(join(cacheDir, 'eslint/'))).toBe(false)
})
test('the default eslint cache lives in the user defined build directory', async () => {
const oldCacheDir = join(dirEslintCacheCustomDir, '.next', 'cache')
const newCacheDir = join(dirEslintCacheCustomDir, 'build', 'cache')
await fs.remove(oldCacheDir)
await fs.remove(newCacheDir)
await nextLint(dirEslintCacheCustomDir, [])
expect(fs.existsSync(oldCacheDir)).toBe(false)
const files = await fs.readdir(join(newCacheDir, 'eslint/'))
const cacheExists = files.some((f) => /\.cache/.test(f))
expect(cacheExists).toBe(true)
})
test('the --cache-location flag allows the user to define a separate cache location', async () => {
const cacheFile = join(dirEslintCache, '.eslintcache')
await fs.remove(cacheFile)
await nextLint(dirEslintCache, ['--cache-location', cacheFile])
const hasCache = fs.existsSync(cacheFile)
await fs.remove(cacheFile) // remove after generate
expect(hasCache).toBe(true)
})
const getEslintCacheContent = async (cacheDir) => {
const eslintCacheDir = join(cacheDir, 'eslint/')
let files = await fs.readdir(eslintCacheDir)
let cacheFiles = files.filter((f) => /\.cache/.test(f))
expect(cacheFiles.length).toBe(1)
const cacheFile = join(eslintCacheDir, cacheFiles[0])
return await fs.readFile(cacheFile, 'utf8')
}
test('the default eslint caching strategy is metadata', async () => {
const cacheDir = join(dirEslintCache, '.next', 'cache')
await fs.remove(cacheDir)
await nextLint(dirEslintCache)
const defaultStrategyCache = await getEslintCacheContent(cacheDir)
await fs.remove(cacheDir)
await nextLint(dirEslintCache, ['--cache-strategy', 'metadata'])
const metadataStrategyCache = await getEslintCacheContent(cacheDir)
expect(metadataStrategyCache).toBe(defaultStrategyCache)
})
test('cache with content strategy is different from the one with default strategy', async () => {
const cacheDir = join(dirEslintCache, '.next', 'cache')
await fs.remove(cacheDir)
await nextLint(dirEslintCache)
const defaultStrategyCache = await getEslintCacheContent(cacheDir)
await fs.remove(cacheDir)
await nextLint(dirEslintCache, ['--cache-strategy', 'content'])
const contentStrategyCache = await getEslintCacheContent(cacheDir)
expect(contentStrategyCache).not.toBe(defaultStrategyCache)
})
test('file flag can selectively lint only a single file', async () => {
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--file', 'utils/math.js'],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain('utils/math.js')
expect(output).toContain(
'Comments inside children section of tag should be placed inside braces'
)
expect(output).not.toContain('pages/')
expect(output).not.toContain('External synchronous scripts are forbidden')
})
test('file flag can selectively lints multiple files', async () => {
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--file', 'utils/math.js', '--file', 'pages/bar.js'],
{
stdout: true,
stderr: true,
}
)
const output = stdout + stderr
expect(output).toContain('utils/math.js')
expect(output).toContain(
'Comments inside children section of tag should be placed inside braces'
)
expect(output).toContain('pages/bar.js')
expect(output).toContain(
"Do not use <img>. Use Image from 'next/image' instead"
)
expect(output).not.toContain('pages/index.js')
expect(output).not.toContain('External synchronous scripts are forbidden')
})
test('output flag create a file respecting the chosen format', async () => {
const filePath = `${__dirname}/output/output.json`
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--format', 'json', '--output-file', filePath],
{
stdout: true,
stderr: true,
}
)
const cliOutput = stdout + stderr
const fileOutput = await fs.readJSON(filePath)
expect(cliOutput).toContain(
`The output file has been created: ${filePath}`
)
if (fileOutput && fileOutput.length) {
fileOutput.forEach((file) => {
expect(file).toHaveProperty('filePath')
expect(file).toHaveProperty('messages')
expect(file).toHaveProperty('errorCount')
expect(file).toHaveProperty('warningCount')
expect(file).toHaveProperty('fixableErrorCount')
expect(file).toHaveProperty('fixableWarningCount')
expect(file).toHaveProperty('source')
expect(file).toHaveProperty('usedDeprecatedRules')
})
expect(fileOutput[0].messages).toEqual(
expect.arrayContaining([
expect.objectContaining({
message:
'img elements must have an alt prop, either with meaningful text, or an empty string for decorative images.',
}),
expect.objectContaining({
message: `Do not use <img>. Use Image from 'next/image' instead. See: https://nextjs.org/docs/messages/no-img-element`,
}),
])
)
expect(fileOutput[1].messages).toEqual(
expect.arrayContaining([
expect.objectContaining({
message:
'External synchronous scripts are forbidden. See: https://nextjs.org/docs/messages/no-sync-scripts',
}),
])
)
}
})
test('output flag create a file respecting the chosen format', async () => {
const filePath = `${__dirname}/output/output.txt`
const { stdout, stderr } = await nextLint(
dirFileLinting,
['--format', 'compact', '--output-file', filePath],
{
stdout: true,
stderr: true,
}
)
const cliOutput = stdout + stderr
const fileOutput = fs.readFileSync(filePath, 'utf8')
expect(cliOutput).toContain(
`The output file has been created: ${filePath}`
)
expect(fileOutput).toContain('file-linting/pages/bar.js')
expect(fileOutput).toContain(
'img elements must have an alt prop, either with meaningful text, or an empty string for decorative images.'
)
expect(fileOutput).toContain(
`Do not use <img>. Use Image from 'next/image' instead. See: https://nextjs.org/docs/messages/no-img-element`
)
expect(fileOutput).toContain('file-linting/pages/index.js')
expect(fileOutput).toContain(
'External synchronous scripts are forbidden. See: https://nextjs.org/docs/messages/no-sync-scripts'
)
})
})
})