/
runAll.spec.js
404 lines (350 loc) Β· 13.2 KB
/
runAll.spec.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
import path from 'path'
import makeConsoleMock from 'consolemock'
import execa from 'execa'
import normalize from 'normalize-path'
import { getStagedFiles } from '../lib/getStagedFiles'
import { GitWorkflow } from '../lib/gitWorkflow'
import { resolveGitRepo } from '../lib/resolveGitRepo'
import { runAll } from '../lib/runAll'
import { ConfigNotFoundError, GitError } from '../lib/symbols'
import * as searchConfigsNS from '../lib/searchConfigs'
import * as getConfigGroupsNS from '../lib/getConfigGroups'
jest.mock('../lib/file')
jest.mock('../lib/getStagedFiles')
jest.mock('../lib/gitWorkflow')
jest.mock('../lib/resolveGitRepo')
jest.mock('../lib/resolveConfig', () => ({
/** Unfortunately necessary due to non-ESM tests. */
resolveConfig: (configPath) => {
try {
return require.resolve(configPath)
} catch {
return configPath
}
},
}))
const searchConfigs = jest.spyOn(searchConfigsNS, 'searchConfigs')
const getConfigGroups = jest.spyOn(getConfigGroupsNS, 'getConfigGroups')
getStagedFiles.mockImplementation(async () => [])
resolveGitRepo.mockImplementation(async () => {
const cwd = process.cwd()
return { gitConfigDir: normalize(path.resolve(cwd, '.git')), gitDir: normalize(cwd) }
})
const configPath = '.lintstagedrc.json'
describe('runAll', () => {
const globalConsoleTemp = console
beforeAll(() => {
console = makeConsoleMock()
})
afterEach(() => {
console.clearHistory()
})
afterAll(() => {
console = globalConsoleTemp
})
it('should resolve the promise with no tasks', async () => {
expect.assertions(1)
await expect(runAll({ configObject: {}, configPath })).resolves.toMatchInlineSnapshot(`
Object {
"errors": Set {},
"hasPartiallyStagedFiles": null,
"output": Array [
"β No staged files found.",
],
"quiet": false,
"shouldBackup": true,
}
`)
})
it('should throw when failed to find staged files', async () => {
expect.assertions(1)
getStagedFiles.mockImplementationOnce(async () => null)
await expect(
runAll({ configObject: {}, configPath })
).rejects.toThrowErrorMatchingInlineSnapshot(`"lint-staged failed"`)
})
it('should throw when failed to find staged files and quiet', async () => {
expect.assertions(1)
getStagedFiles.mockImplementationOnce(async () => null)
await expect(
runAll({ configObject: {}, configPath, quiet: true })
).rejects.toThrowErrorMatchingInlineSnapshot(`"lint-staged failed"`)
})
it('should print output when no staged files', async () => {
expect.assertions(1)
await expect(runAll({ configObject: {}, configPath })).resolves.toMatchInlineSnapshot(`
Object {
"errors": Set {},
"hasPartiallyStagedFiles": null,
"output": Array [
"β No staged files found.",
],
"quiet": false,
"shouldBackup": true,
}
`)
})
it('should not print output when no staged files and quiet', async () => {
expect.assertions(1)
await expect(runAll({ configObject: {}, configPath, quiet: true })).resolves
.toMatchInlineSnapshot(`
Object {
"errors": Set {},
"hasPartiallyStagedFiles": null,
"output": Array [],
"quiet": true,
"shouldBackup": true,
}
`)
})
it('should resolve the promise with no files', async () => {
expect.assertions(1)
await runAll({ configObject: { '*.js': ['echo "sample"'] }, configPath })
expect(console.printHistory()).toMatchInlineSnapshot(`""`)
})
it('should use an injected logger', async () => {
expect.assertions(1)
const logger = makeConsoleMock()
await runAll({ configObject: { '*.js': ['echo "sample"'] }, configPath, debug: true }, logger)
expect(logger.printHistory()).toMatchInlineSnapshot(`""`)
})
it('should exit without output when no staged files match configured tasks and quiet', async () => {
expect.assertions(1)
getStagedFiles.mockImplementationOnce(async () => ['sample.js'])
await runAll({ configObject: { '*.css': ['echo "sample"'] }, configPath, quiet: true })
expect(console.printHistory()).toMatchInlineSnapshot(`""`)
})
it('should not skip tasks if there are files', async () => {
expect.assertions(1)
getStagedFiles.mockImplementationOnce(async () => ['sample.js'])
await runAll({ configObject: { '*.js': ['echo "sample"'] }, configPath })
expect(console.printHistory()).toMatchInlineSnapshot(`
"
LOG [STARTED] Preparing lint-staged...
LOG [SUCCESS] Preparing lint-staged...
LOG [STARTED] Running tasks for staged files...
LOG [STARTED] β 1 file
LOG [STARTED] *.js β 1 file
LOG [STARTED] echo \\"sample\\"
LOG [SUCCESS] echo \\"sample\\"
LOG [SUCCESS] *.js β 1 file
LOG [SUCCESS] β 1 file
LOG [SUCCESS] Running tasks for staged files...
LOG [STARTED] Applying modifications from tasks...
LOG [SUCCESS] Applying modifications from tasks...
LOG [STARTED] Cleaning up temporary files...
LOG [SUCCESS] Cleaning up temporary files..."
`)
})
it('should skip tasks if previous git error', async () => {
expect.assertions(2)
getStagedFiles.mockImplementationOnce(async () => ['sample.js'])
GitWorkflow.mockImplementationOnce(() => ({
...jest.requireActual('../lib/gitWorkflow'),
prepare: (ctx) => {
ctx.errors.add(GitError)
throw new Error('test')
},
}))
await expect(
runAll({ configObject: { '*.js': ['echo "sample"'] }, configPath })
).rejects.toThrowErrorMatchingInlineSnapshot(`"lint-staged failed"`)
expect(console.printHistory()).toMatchInlineSnapshot(`
"
LOG [STARTED] Preparing lint-staged...
ERROR [FAILED] test
LOG [STARTED] Running tasks for staged files...
INFO [SKIPPED] Running tasks for staged files...
LOG [STARTED] Applying modifications from tasks...
INFO [SKIPPED]
[SKIPPED] β lint-staged failed due to a git error.
LOG [STARTED] Cleaning up temporary files...
INFO [SKIPPED]
[SKIPPED] β lint-staged failed due to a git error."
`)
})
it('should skip applying unstaged modifications if there are errors during linting', async () => {
expect.assertions(2)
getStagedFiles.mockImplementationOnce(async () => ['sample.js'])
execa.mockImplementation(() =>
Promise.resolve({
stdout: '',
stderr: 'Linter finished with error',
code: 1,
failed: true,
cmd: 'mock cmd',
})
)
await expect(
runAll({ configObject: { '*.js': ['echo "sample"'] }, configPath })
).rejects.toThrowErrorMatchingInlineSnapshot(`"lint-staged failed"`)
expect(console.printHistory()).toMatchInlineSnapshot(`
"
LOG [STARTED] Preparing lint-staged...
LOG [SUCCESS] Preparing lint-staged...
LOG [STARTED] Running tasks for staged files...
LOG [STARTED] β 1 file
LOG [STARTED] *.js β 1 file
LOG [STARTED] echo \\"sample\\"
ERROR [FAILED] echo \\"sample\\" [1]
ERROR [FAILED] echo \\"sample\\" [1]
LOG [SUCCESS] Running tasks for staged files...
LOG [STARTED] Applying modifications from tasks...
INFO [SKIPPED] Skipped because of errors from tasks.
LOG [STARTED] Reverting to original state because of errors...
LOG [SUCCESS] Reverting to original state because of errors...
LOG [STARTED] Cleaning up temporary files...
LOG [SUCCESS] Cleaning up temporary files..."
`)
})
it('should skip tasks and restore state if terminated', async () => {
expect.assertions(2)
getStagedFiles.mockImplementationOnce(async () => ['sample.js'])
execa.mockImplementation(() =>
Promise.resolve({
stdout: '',
stderr: '',
code: 0,
failed: false,
killed: true,
signal: 'SIGINT',
cmd: 'mock cmd',
})
)
await expect(
runAll({ configObject: { '*.js': ['echo "sample"'] }, configPath })
).rejects.toThrowErrorMatchingInlineSnapshot(`"lint-staged failed"`)
expect(console.printHistory()).toMatchInlineSnapshot(`
"
LOG [STARTED] Preparing lint-staged...
LOG [SUCCESS] Preparing lint-staged...
LOG [STARTED] Running tasks for staged files...
LOG [STARTED] β 1 file
LOG [STARTED] *.js β 1 file
LOG [STARTED] echo \\"sample\\"
ERROR [FAILED] echo \\"sample\\" [SIGINT]
ERROR [FAILED] echo \\"sample\\" [SIGINT]
LOG [SUCCESS] Running tasks for staged files...
LOG [STARTED] Applying modifications from tasks...
INFO [SKIPPED] Skipped because of errors from tasks.
LOG [STARTED] Reverting to original state because of errors...
LOG [SUCCESS] Reverting to original state because of errors...
LOG [STARTED] Cleaning up temporary files...
LOG [SUCCESS] Cleaning up temporary files..."
`)
})
it('should resolve matched files to cwd when using relative option', async () => {
// A staged file inside test/, which will be our cwd
getStagedFiles.mockImplementationOnce(async () => ['test/foo.js'])
// We are only interested in the `matchedFileChunks` generation
let expected
const mockConstructor = jest.fn(({ matchedFileChunks }) => (expected = matchedFileChunks))
GitWorkflow.mockImplementationOnce(mockConstructor)
const mockTask = jest.fn(() => ['echo "sample"'])
// actual cwd
const cwd = process.cwd()
// For the test, set cwd in test/
const innerCwd = path.join(cwd, 'test/')
// Run lint-staged in `innerCwd` with relative option
// This means the sample task will receive `foo.js`
await expect(
runAll({
configObject: { '*.js': mockTask },
configPath,
stash: false,
relative: true,
cwd: innerCwd,
})
).rejects.toThrowError()
// task received relative `foo.js`
expect(mockTask).toHaveBeenCalledTimes(1)
expect(mockTask).toHaveBeenCalledWith(['foo.js'])
// GitWorkflow received absolute `test/foo.js`
expect(mockConstructor).toHaveBeenCalledTimes(1)
expect(expected).toEqual([[normalize(path.join(cwd, 'test/foo.js'))]])
})
it('should resolve matched files to config locations with multiple configs', async () => {
getStagedFiles.mockImplementationOnce(async () => ['foo.js', 'test/foo.js'])
const mockTask = jest.fn(() => ['echo "sample"'])
getConfigGroups.mockResolvedValueOnce({
'.lintstagedrc.json': {
config: { '*.js': mockTask },
files: ['foo.js'],
},
'test/.lintstagedrc.json': {
config: { '*.js': mockTask },
files: ['test/foo.js'],
},
})
searchConfigs.mockResolvedValueOnce({
'.lintstagedrc.json': { '*.js': mockTask },
'test/.lintstagedrc.json': { '*.js': mockTask },
})
// We are only interested in the `matchedFileChunks` generation
let expected
const mockConstructor = jest.fn(({ matchedFileChunks }) => (expected = matchedFileChunks))
GitWorkflow.mockImplementationOnce(mockConstructor)
await expect(
runAll({
stash: false,
relative: true,
})
).rejects.toThrowError()
// task received relative `foo.js` from both directories
expect(mockTask).toHaveBeenCalledTimes(2)
expect(mockTask).toHaveBeenNthCalledWith(1, ['foo.js'])
expect(mockTask).toHaveBeenNthCalledWith(2, ['foo.js'])
// GitWorkflow received absolute paths `foo.js` and `test/foo.js`
expect(mockConstructor).toHaveBeenCalledTimes(1)
expect(expected).toEqual([
[
normalize(path.join(process.cwd(), 'foo.js')),
normalize(path.join(process.cwd(), 'test/foo.js')),
],
])
})
it('should resolve matched files to explicit cwd with multiple configs', async () => {
getStagedFiles.mockImplementationOnce(async () => ['foo.js', 'test/foo.js'])
const mockTask = jest.fn(() => ['echo "sample"'])
getConfigGroups.mockResolvedValueOnce({
'.lintstagedrc.json': {
config: { '*.js': mockTask },
files: ['foo.js'],
},
'test/.lintstagedrc.json': {
config: { '*.js': mockTask },
files: ['test/foo.js'],
},
})
searchConfigs.mockResolvedValueOnce({
'.lintstagedrc.json': { '*.js': mockTask },
'test/.lintstagedrc.json': { '*.js': mockTask },
})
await expect(
runAll({
cwd: '.',
stash: false,
relative: true,
})
).rejects.toThrowError()
expect(mockTask).toHaveBeenCalledTimes(2)
expect(mockTask).toHaveBeenNthCalledWith(1, ['foo.js'])
// This is now relative to "." instead of "test/"
expect(mockTask).toHaveBeenNthCalledWith(2, ['test/foo.js'])
})
it('should error when no configurations found', async () => {
getStagedFiles.mockImplementationOnce(async () => ['foo.js', 'test/foo.js'])
getConfigGroups.mockResolvedValueOnce({})
searchConfigs.mockResolvedValueOnce({})
expect.assertions(1)
try {
await runAll({
cwd: '.',
stash: false,
relative: true,
})
} catch ({ ctx }) {
expect(ctx.errors.has(ConfigNotFoundError)).toBe(true)
}
})
})