Skip to content

Commit 22fb027

Browse files
committedJul 6, 2024
feat(cli): allow migrating cjs presets to transform config
1 parent 72074d2 commit 22fb027

File tree

3 files changed

+284
-253
lines changed

3 files changed

+284
-253
lines changed
 

‎src/cli/__snapshots__/cli.spec.ts.snap

+76-20
Original file line numberDiff line numberDiff line change
@@ -110,44 +110,80 @@ exports[`config init should update package.json for config type js-with-ts-full-
110110
}"
111111
`;
112112

113-
exports[`config migrate should migrate globals ts-jest config to transformer config 1`] = `
114-
""jest": {
115-
"transform": {
116-
"^.+\\\\.tsx?$": [
117-
"ts-jest",
118-
{
119-
"tsconfig": "./tsconfig.json"
120-
}
121-
]
113+
exports[`config migrate should generate transform config with existing transform options for js-with-babel 1`] = `
114+
"module.exports = {
115+
transform: {
116+
'^.+.jsx?$': 'babel-jest',
117+
'^.+.tsx?$': [
118+
'ts-jest',
119+
{},
120+
],
121+
},
122+
}
123+
"
124+
`;
125+
126+
exports[`config migrate should generate transform config with existing transform options for js-with-ts 1`] = `
127+
"module.exports = {
128+
transform: {
129+
'^.+.[tj]sx?$': [
130+
'ts-jest',
131+
{},
132+
],
133+
'^.+.tsx?$': [
134+
'ts-jest',
135+
{},
136+
],
122137
},
123-
"preset": "ts-jest/presets/js-with-babel"
124138
}
125139
"
126140
`;
127141

128142
exports[`config migrate should migrate preset if valid preset value is used 1`] = `
143+
""jest": {
144+
"transform": {
145+
"^.+.tsx?$": [
146+
"ts-jest",
147+
{}
148+
]
149+
}
150+
}
129151
"
130-
No migration needed for given Jest configuration
131-
"
132152
`;
133153

134154
exports[`config migrate should migrate preset if valid preset value is used 2`] = `
135155
""jest": {
136-
"preset": "ts-jest"
156+
"transform": {
157+
"^.+.tsx?$": [
158+
"ts-jest",
159+
{}
160+
]
161+
}
137162
}
138163
"
139164
`;
140165

141166
exports[`config migrate should migrate preset if valid preset value is used 3`] = `
167+
""jest": {
168+
"transform": {
169+
"^.+.tsx?$": [
170+
"ts-jest",
171+
{}
172+
]
173+
}
174+
}
142175
"
143-
No migration needed for given Jest configuration
144-
"
145176
`;
146177

147178
exports[`config migrate should reset testMatch if testRegex is used 1`] = `
148179
""jest": {
149180
"testRegex": "foo-pattern",
150-
"preset": "ts-jest"
181+
"transform": {
182+
"^.+.tsx?$": [
183+
"ts-jest",
184+
{}
185+
]
186+
}
151187
}
152188
"
153189
`;
@@ -157,7 +193,12 @@ exports[`config migrate should reset testMatch if testRegex is used 2`] = `
157193
"testRegex": [
158194
"foo-pattern"
159195
],
160-
"preset": "ts-jest"
196+
"transform": {
197+
"^.+.tsx?$": [
198+
"ts-jest",
199+
{}
200+
]
201+
}
161202
}
162203
"
163204
`;
@@ -168,7 +209,12 @@ exports[`config migrate should reset testMatch if testRegex is used 3`] = `
168209
"testMatch": [
169210
"**/__tests__/**/*.(spec|test).[tj]s?(x)"
170211
],
171-
"preset": "ts-jest"
212+
"transform": {
213+
"^.+.tsx?$": [
214+
"ts-jest",
215+
{}
216+
]
217+
}
172218
}
173219
"
174220
`;
@@ -178,15 +224,25 @@ exports[`config migrate should reset testMatch if testRegex is used 4`] = `
178224
"testMatch": [
179225
"**/__tests__/**/*.(spec|test).[tj]s?(x)"
180226
],
181-
"preset": "ts-jest"
227+
"transform": {
228+
"^.+.tsx?$": [
229+
"ts-jest",
230+
{}
231+
]
232+
}
182233
}
183234
"
184235
`;
185236

186237
exports[`config migrate should reset testMatch if testRegex is used 5`] = `
187238
""jest": {
188239
"testRegex": "foo-pattern",
189-
"preset": "ts-jest"
240+
"transform": {
241+
"^.+.tsx?$": [
242+
"ts-jest",
243+
{}
244+
]
245+
}
190246
}
191247
"
192248
`;

‎src/cli/cli.spec.ts

+148-93
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as _fs from 'fs'
22
import { normalize, resolve } from 'path'
33

44
import { logTargetMock, mockObject, mockWriteStream } from '../__helpers__/mocks'
5+
import { JS_TRANSFORM_PATTERN, TS_JS_TRANSFORM_PATTERN, TS_TRANSFORM_PATTERN } from '../constants'
56

67
import { processArgv } from '.'
78

@@ -261,32 +262,38 @@ describe('config', () => {
261262
jest.mock(
262263
pkgPaths.next,
263264
() => ({
264-
jest: { globals: { __TS_CONFIG__: { target: 'es6' } } },
265+
jest: {
266+
globals: {
267+
'ts-jest': {
268+
tsconfig: { target: 'es6' },
269+
},
270+
},
271+
},
265272
}),
266273
{ virtual: true },
267274
)
275+
268276
const res = await runCli(...noOption, pkgPaths.current)
277+
269278
expect(res).toMatchInlineSnapshot(`
270279
{
271280
"exitCode": 0,
272-
"log": "",
281+
"log": "[level:20] creating default CJS Jest preset
282+
",
273283
"stderr": "
274284
Migrated Jest configuration:
275-
276-
277-
Detected preset 'default' as the best matching preset for your configuration.
278-
Visit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more information about presets.
279-
280285
",
281286
"stdout": ""jest": {
282-
"globals": {
283-
"ts-jest": {
284-
"tsconfig": {
285-
"target": "es6"
287+
"transform": {
288+
"^.+.tsx?$": [
289+
"ts-jest",
290+
{
291+
"tsconfig": {
292+
"target": "es6"
293+
}
286294
}
287-
}
288-
},
289-
"preset": "ts-jest"
295+
]
296+
}
290297
}
291298
",
292299
}
@@ -300,25 +307,37 @@ describe('config', () => {
300307
jest.mock(
301308
pkgPaths.next,
302309
() => ({
303-
jest: { globals: { __TS_CONFIG__: { target: 'es6' } } },
310+
jest: {
311+
globals: {
312+
'ts-jest': {
313+
tsconfig: { target: 'es6' },
314+
},
315+
},
316+
},
304317
}),
305318
{ virtual: true },
306319
)
320+
307321
const res = await runCli(...fullOptions, pkgPaths.current)
322+
308323
expect(res).toMatchInlineSnapshot(`
309324
{
310325
"exitCode": 0,
311-
"log": "",
326+
"log": "[level:20] creating Js with Ts CJS Jest preset
327+
",
312328
"stderr": "
313329
Migrated Jest configuration:
314330
",
315331
"stdout": ""jest": {
316-
"globals": {
317-
"ts-jest": {
318-
"tsconfig": {
319-
"target": "es6"
332+
"transform": {
333+
"^.+.[tj]sx?$": [
334+
"ts-jest",
335+
{
336+
"tsconfig": {
337+
"target": "es6"
338+
}
320339
}
321-
}
340+
]
322341
}
323342
}
324343
",
@@ -327,14 +346,18 @@ describe('config', () => {
327346
expect(fs.writeFileSync).not.toHaveBeenCalled()
328347
})
329348

330-
it('should detect same option values', async () => {
349+
it('should generate transform options while keeping other jest config options', async () => {
331350
expect.assertions(1)
332351
fs.existsSync.mockImplementation(() => true)
333352
jest.mock(
334353
pkgPaths.next,
335354
() => ({
336355
jest: {
337-
globals: { __TS_CONFIG__: { target: 'es6' } },
356+
globals: {
357+
'ts-jest': {
358+
tsconfig: { target: 'es6' },
359+
},
360+
},
338361
moduleFileExtensions: ['ts', 'tsx', 'js'],
339362
testMatch: [
340363
'**/__tests__/**/*.js?(x)',
@@ -346,16 +369,11 @@ describe('config', () => {
346369
}),
347370
{ virtual: true },
348371
)
372+
349373
const res = await runCli(...noOption, pkgPaths.current)
374+
350375
expect(res.stdout).toMatchInlineSnapshot(`
351376
""jest": {
352-
"globals": {
353-
"ts-jest": {
354-
"tsconfig": {
355-
"target": "es6"
356-
}
357-
}
358-
},
359377
"moduleFileExtensions": [
360378
"js",
361379
"ts",
@@ -367,13 +385,22 @@ describe('config', () => {
367385
"**/__tests__/**/*.js?(x)",
368386
"**/__tests__/**/*.ts?(x)"
369387
],
370-
"preset": "ts-jest"
388+
"transform": {
389+
"^.+.tsx?$": [
390+
"ts-jest",
391+
{
392+
"tsconfig": {
393+
"target": "es6"
394+
}
395+
}
396+
]
397+
}
371398
}
372399
"
373400
`)
374401
})
375402

376-
test.each([
403+
it.each([
377404
{
378405
jest: {
379406
preset: 'ts-jest',
@@ -399,7 +426,7 @@ describe('config', () => {
399426
expect(res.stdout ? res.stdout : res.stderr).toMatchSnapshot()
400427
})
401428

402-
test.each([
429+
it.each([
403430
{
404431
jest: {
405432
testRegex: 'foo-pattern',
@@ -438,67 +465,102 @@ describe('config', () => {
438465
expect(res.stdout).toMatchSnapshot()
439466
})
440467

441-
it('should detect best preset', async () => {
442-
expect.assertions(5)
468+
it('should generate transform config with default CLI options', async () => {
443469
fs.existsSync.mockImplementation(() => true)
444470
jest.mock(pkgPaths.next, () => ({}), { virtual: true })
445-
446-
// defaults
447471
jest.doMock(pkgPaths.nextCfg, () => ({}), { virtual: true })
448-
let res = await runCli(...noOption, pkgPaths.currentCfg)
472+
473+
const res = await runCli(...noOption, pkgPaths.currentCfg)
474+
449475
expect(res.stdout).toMatchInlineSnapshot(`
450476
"module.exports = {
451-
preset: 'ts-jest',
477+
transform: {
478+
'^.+.tsx?$': [
479+
'ts-jest',
480+
{},
481+
],
482+
},
452483
}
453484
"
454485
`)
486+
})
455487

456-
// js-with-ts from args
488+
it('should generate transform config with allow-js in CLI options', async () => {
489+
fs.existsSync.mockImplementation(() => true)
490+
jest.mock(pkgPaths.next, () => ({}), { virtual: true })
457491
jest.doMock(pkgPaths.nextCfg, () => ({}), { virtual: true })
458-
res = await runCli(...noOption, '--allow-js', pkgPaths.currentCfg)
459-
expect(res.stdout).toMatchInlineSnapshot(`
460-
"module.exports = {
461-
preset: 'ts-jest/presets/js-with-ts',
462-
}
463-
"
464-
`)
465492

466-
// js-with-ts from previous transform
467-
jest.doMock(pkgPaths.nextCfg, () => ({ transform: { '^.+\\.[tj]sx?$': 'ts-jest' } }), { virtual: true })
468-
res = await runCli(...noOption, pkgPaths.currentCfg)
469-
expect(res.stdout).toMatchInlineSnapshot(`
470-
"module.exports = {
471-
preset: 'ts-jest/presets/js-with-ts',
472-
}
473-
"
474-
`)
493+
const res = await runCli(...noOption, '--allow-js', pkgPaths.currentCfg)
475494

476-
// js-with-babel from previous transform
477-
jest.doMock(pkgPaths.nextCfg, () => ({ transform: { '^.+\\.jsx?$': 'babel-jest', '^.+\\.tsx?$': 'ts-jest' } }), {
478-
virtual: true,
479-
})
480-
res = await runCli(...noOption, pkgPaths.currentCfg)
481495
expect(res.stdout).toMatchInlineSnapshot(`
482496
"module.exports = {
483-
preset: 'ts-jest/presets/js-with-babel',
497+
transform: {
498+
'^.+.[tj]sx?$': [
499+
'ts-jest',
500+
{},
501+
],
502+
},
484503
}
485504
"
486505
`)
506+
})
487507

488-
// defaults when previous transform is ambiguous
508+
it.each([
509+
{
510+
name: 'js-with-babel',
511+
transform: {
512+
[JS_TRANSFORM_PATTERN]: 'babel-jest',
513+
[TS_TRANSFORM_PATTERN]: 'ts-jest',
514+
},
515+
},
516+
{
517+
name: 'js-with-ts',
518+
transform: {
519+
[TS_JS_TRANSFORM_PATTERN]: 'ts-jest',
520+
},
521+
},
522+
])('should generate transform config with existing transform options for $name', async ({ transform }) => {
523+
fs.existsSync.mockImplementation(() => true)
524+
jest.mock(pkgPaths.next, () => ({}), { virtual: true })
525+
jest.doMock(
526+
pkgPaths.nextCfg,
527+
() => ({
528+
transform,
529+
}),
530+
{
531+
virtual: true,
532+
},
533+
)
534+
535+
const res = await runCli(...noOption, pkgPaths.currentCfg)
536+
537+
expect(res.stdout).toMatchSnapshot()
538+
})
539+
540+
it('should generate transform config by merging existing transform options with default transform options', async () => {
541+
fs.existsSync.mockImplementation(() => true)
542+
jest.mock(pkgPaths.next, () => ({}), { virtual: true })
489543
jest.doMock(
490544
pkgPaths.nextCfg,
491545
() => ({ transform: { '^src/js/.+\\.jsx?$': 'babel-jest', '^src/ts/.+\\.tsx?$': 'ts-jest' } }),
492546
{ virtual: true },
493547
)
494-
res = await runCli(...noOption, pkgPaths.currentCfg)
548+
549+
const res = await runCli(...noOption, pkgPaths.currentCfg)
550+
495551
expect(res.stdout).toMatchInlineSnapshot(`
496552
"module.exports = {
497553
transform: {
498554
'^src/js/.+\\\\.jsx?$': 'babel-jest',
499-
'^src/ts/.+\\\\.tsx?$': 'ts-jest',
555+
'^src/ts/.+\\\\.tsx?$': [
556+
'ts-jest',
557+
{},
558+
],
559+
'^.+.tsx?$': [
560+
'ts-jest',
561+
{},
562+
],
500563
},
501-
preset: 'ts-jest',
502564
}
503565
"
504566
`)
@@ -520,22 +582,37 @@ describe('config', () => {
520582
}),
521583
{ virtual: true },
522584
)
585+
523586
const res = await runCli(...noOption, pkgPaths.current)
587+
524588
expect(res.stdout).toMatchInlineSnapshot(`
525589
""jest": {
526590
"transform": {
527-
"<rootDir>/src/.+\\\\.[jt]s$": "ts-jest",
528-
"foo\\\\.ts": "ts-jest",
529-
"bar\\\\.ts": "ts-jest"
530-
},
531-
"preset": "ts-jest"
591+
"<rootDir>/src/.+\\\\.[jt]s$": [
592+
"ts-jest",
593+
{}
594+
],
595+
"foo\\\\.ts": [
596+
"ts-jest",
597+
{}
598+
],
599+
"bar\\\\.ts": [
600+
"ts-jest",
601+
{}
602+
],
603+
"^.+.tsx?$": [
604+
"ts-jest",
605+
{}
606+
]
607+
}
532608
}
533609
"
534610
`)
535611
})
536612

537613
it('should output help', async () => {
538614
const res = await runCli('help', noOption[0])
615+
539616
expect(res).toMatchInlineSnapshot(`
540617
{
541618
"exitCode": 0,
@@ -558,27 +635,5 @@ describe('config', () => {
558635
}
559636
`)
560637
})
561-
562-
it('should migrate globals ts-jest config to transformer config', async () => {
563-
fs.existsSync.mockImplementation(() => true)
564-
jest.mock(
565-
pkgPaths.next,
566-
() => ({
567-
jest: {
568-
globals: {
569-
'ts-jest': {
570-
tsconfig: './tsconfig.json',
571-
},
572-
},
573-
transform: { '^.+\\.jsx?$': 'babel-jest', '^.+\\.tsx?$': 'ts-jest' },
574-
},
575-
}),
576-
{ virtual: true },
577-
)
578-
579-
const res = await runCli(...noOption, pkgPaths.current)
580-
581-
expect(res.stdout).toMatchSnapshot()
582-
})
583638
}) // migrate
584639
})

‎src/cli/config/migrate.ts

+60-140
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,56 @@ import stableStringify from 'fast-json-stable-stringify'
77
import { stringify as stringifyJson5 } from 'json5'
88

99
import type { CliCommand, CliCommandArgs } from '..'
10+
import { createDefaultPreset, createJsWithBabelPreset, createJsWithTsPreset } from '../../presets/create-jest-preset'
11+
import type { TsJestTransformerOptions } from '../../types'
1012
import { backportJestConfig } from '../../utils/backports'
11-
import { JestPresetNames, TsJestPresetDescriptor, allPresets, defaults } from '../helpers/presets'
13+
import { JestPresetNames, type TsJestPresetDescriptor, allPresets } from '../helpers/presets'
14+
15+
const migrateGlobalConfigToTransformConfig = (
16+
transformConfig: Config.InitialOptions['transform'],
17+
globalsTsJestConfig: TsJestTransformerOptions | undefined,
18+
) => {
19+
if (transformConfig) {
20+
return Object.entries(transformConfig).reduce((previousValue, currentValue) => {
21+
const [key, transformOptions] = currentValue
22+
if (typeof transformOptions === 'string' && transformOptions.includes('ts-jest')) {
23+
return {
24+
...previousValue,
25+
[key]: globalsTsJestConfig ? ['ts-jest', globalsTsJestConfig] : 'ts-jest',
26+
}
27+
}
28+
29+
return {
30+
...previousValue,
31+
[key]: transformOptions,
32+
}
33+
}, {})
34+
}
35+
36+
return {}
37+
}
38+
39+
const migratePresetToTransformConfig = (
40+
transformConfig: Config.InitialOptions['transform'],
41+
preset: TsJestPresetDescriptor | undefined,
42+
globalsTsJestConfig: TsJestTransformerOptions | undefined,
43+
) => {
44+
if (preset) {
45+
const transformConfigFromPreset =
46+
preset.name === JestPresetNames.jsWithTs
47+
? createJsWithTsPreset(globalsTsJestConfig)
48+
: preset.name === JestPresetNames.jsWIthBabel
49+
? createJsWithBabelPreset(globalsTsJestConfig)
50+
: createDefaultPreset(globalsTsJestConfig)
51+
52+
return {
53+
...transformConfig,
54+
...transformConfigFromPreset.transform,
55+
}
56+
}
57+
58+
return transformConfig
59+
}
1260

1361
/**
1462
* @internal
@@ -17,7 +65,6 @@ export const run: CliCommand = async (args: CliCommandArgs /* , logger: Logger*/
1765
const nullLogger = createLogger({ targets: [] })
1866
const file = args._[0]?.toString()
1967
const filePath = resolve(process.cwd(), file)
20-
const footNotes: string[] = []
2168
if (!existsSync(filePath)) {
2269
throw new Error(`Configuration file ${file} does not exists.`)
2370
}
@@ -36,59 +83,18 @@ export const run: CliCommand = async (args: CliCommandArgs /* , logger: Logger*/
3683
// migrate
3784
// first we backport our options
3885
const migratedConfig = backportJestConfig(nullLogger, actualConfig)
39-
let presetName: JestPresetNames | undefined
4086
let preset: TsJestPresetDescriptor | undefined
41-
// then we check if we can use `preset`
42-
if (!migratedConfig.preset && args.jestPreset) {
43-
// find the best preset
87+
if (migratedConfig.preset) {
88+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
89+
preset = (allPresets as any)[migratedConfig.preset] ?? allPresets[JestPresetNames.default]
90+
} else {
4491
if (args.js) {
45-
presetName = args.js === 'babel' ? JestPresetNames.jsWIthBabel : JestPresetNames.jsWithTs
46-
} else {
47-
// try to detect what transformer the js extensions would target
48-
const jsTransformers = Object.keys(migratedConfig.transform || {}).reduce((list, pattern) => {
49-
if (RegExp(pattern.replace(/^<rootDir>\/?/, '/dummy-project/')).test('/dummy-project/src/foo.js')) {
50-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
51-
let transformer: string = (migratedConfig.transform as any)[pattern]
52-
if (/\bbabel-jest\b/.test(transformer)) transformer = 'babel-jest'
53-
else if (/\ts-jest\b/.test(transformer)) transformer = 'ts-jest'
54-
55-
return [...list, transformer]
56-
}
57-
58-
return list
59-
}, [] as string[])
60-
// depending on the transformer found, we use one or the other preset
61-
const jsWithTs = jsTransformers.includes('ts-jest')
62-
const jsWithBabel = jsTransformers.includes('babel-jest')
63-
if (jsWithBabel && !jsWithTs) {
64-
presetName = JestPresetNames.jsWIthBabel
65-
} else if (jsWithTs && !jsWithBabel) {
66-
presetName = JestPresetNames.jsWithTs
67-
} else {
68-
// sounds like js files are NOT handled, or handled with a unknown transformer, so we do not need to handle it
69-
presetName = JestPresetNames.default
70-
}
71-
}
72-
// ensure we are using a preset
73-
presetName = presetName ?? JestPresetNames.default
74-
preset = allPresets[presetName]
75-
footNotes.push(
76-
`Detected preset '${preset.label}' as the best matching preset for your configuration.
77-
Visit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more information about presets.
78-
`,
79-
)
80-
} else if (migratedConfig.preset?.startsWith('ts-jest')) {
81-
if (args.jestPreset === false) {
82-
delete migratedConfig.preset
92+
preset = args.js === 'babel' ? allPresets[JestPresetNames.jsWIthBabel] : allPresets[JestPresetNames.jsWithTs]
8393
} else {
84-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
85-
preset = (allPresets as any)[migratedConfig.preset] ?? defaults
94+
preset = allPresets[JestPresetNames.default]
8695
}
8796
}
8897

89-
// enforce the correct name
90-
if (preset) migratedConfig.preset = preset.name
91-
9298
// check the extensions
9399
if (migratedConfig.moduleFileExtensions?.length && preset) {
94100
const presetValue = dedupSort(preset.value.moduleFileExtensions ?? []).join('::')
@@ -98,7 +104,7 @@ Visit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more inf
98104
}
99105
}
100106
// there is a testRegex, remove our testMatch
101-
if ((typeof migratedConfig.testRegex === 'string' || migratedConfig.testRegex?.length) && preset) {
107+
if (typeof migratedConfig.testRegex === 'string' || migratedConfig.testRegex?.length) {
102108
delete migratedConfig.testMatch
103109
}
104110
// check the testMatch
@@ -110,64 +116,10 @@ Visit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more inf
110116
}
111117
}
112118

113-
// migrate the transform
114-
if (migratedConfig.transform) {
115-
Object.keys(migratedConfig.transform).forEach((key) => {
116-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
117-
const val = (migratedConfig.transform as any)[key]
118-
if (typeof val === 'string' && /\/?ts-jest?(?:\/preprocessor\.js)?$/.test(val)) {
119-
// eslint-disable-next-line
120-
;(migratedConfig.transform as any)[key] = 'ts-jest'
121-
}
122-
})
123-
}
124-
125-
// migrate globals config to transformer config
126119
const globalsTsJestConfig = migratedConfig.globals?.['ts-jest']
127-
if (globalsTsJestConfig && migratedConfig.transform) {
128-
Object.keys(migratedConfig.transform).forEach((key) => {
129-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
130-
const val = (migratedConfig.transform as any)[key]
131-
if (typeof val === 'string' && val.includes('ts-jest')) {
132-
// eslint-disable-next-line
133-
;(migratedConfig.transform as any)[key] = Object.keys(globalsTsJestConfig).length ? [val, globalsTsJestConfig] : val
134-
}
135-
})
136-
delete (migratedConfig.globals ?? Object.create(null))['ts-jest']
137-
}
120+
migratedConfig.transform = migrateGlobalConfigToTransformConfig(migratedConfig.transform, globalsTsJestConfig)
121+
migratedConfig.transform = migratePresetToTransformConfig(migratedConfig.transform, preset, globalsTsJestConfig)
138122

139-
// check if it's the same as the preset's one
140-
if (preset && migratedConfig.transform) {
141-
if (stableStringify(migratedConfig.transform) === stableStringify(preset.value.transform)) {
142-
delete migratedConfig.transform
143-
} else {
144-
const migratedConfigTransform = migratedConfig.transform
145-
const presetValueTransform = preset.value.transform
146-
if (migratedConfigTransform && presetValueTransform) {
147-
migratedConfig.transform = Object.entries(migratedConfigTransform).reduce(
148-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
149-
(acc: undefined | Record<string, any>, [fileRegex, transformerConfig]) => {
150-
const presetValueTransformerConfig = presetValueTransform[fileRegex]
151-
const shouldRemoveDuplicatedConfig =
152-
(presetValueTransformerConfig &&
153-
Array.isArray(presetValueTransformerConfig) &&
154-
transformerConfig === presetValueTransformerConfig[0] &&
155-
!Object.keys(presetValueTransformerConfig[1]).length) ||
156-
transformerConfig === presetValueTransformerConfig
157-
158-
return shouldRemoveDuplicatedConfig
159-
? acc
160-
: acc
161-
? { ...acc, [fileRegex]: transformerConfig }
162-
: { [fileRegex]: transformerConfig }
163-
},
164-
undefined,
165-
)
166-
}
167-
}
168-
}
169-
170-
// cleanup
171123
cleanupConfig(actualConfig)
172124
cleanupConfig(migratedConfig)
173125
const before = stableStringify(actualConfig)
@@ -183,48 +135,16 @@ No migration needed for given Jest configuration
183135
const stringify = file.endsWith('.json') ? JSON.stringify : stringifyJson5
184136
const prefix = file.endsWith('.json') ? '"jest": ' : 'module.exports = '
185137

186-
// if we are using preset, inform the user that he might be able to remove some section(s)
187-
// we couldn't check for equality
188-
// if (usesPreset && migratedConfig.testMatch) {
189-
// footNotes.push(`
190-
// I couldn't check if your "testMatch" value is the same as mine which is: ${stringify(
191-
// presets.testMatch,
192-
// undefined,
193-
// ' ',
194-
// )}
195-
// If it is the case, you can safely remove the "testMatch" from what I've migrated.
196-
// `)
197-
// }
198-
if (preset && migratedConfig.transform) {
199-
footNotes.push(`
200-
I couldn't check if your "transform" value is the same as mine which is: ${stringify(
201-
preset.value.transform,
202-
undefined,
203-
' ',
204-
)}
205-
If it is the case, you can safely remove the "transform" from what I've migrated.
206-
`)
207-
}
208-
209138
// output new config
210139
process.stderr.write(`
211140
Migrated Jest configuration:
212141
`)
213142
process.stdout.write(`${prefix}${stringify(migratedConfig, undefined, ' ')}\n`)
214-
if (footNotes.length) {
215-
process.stderr.write(`
216-
${footNotes.join('\n')}
217-
`)
218-
}
219143
}
220144

221145
function cleanupConfig(config: Config.InitialOptions): void {
222146
if (config.globals) {
223-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
224-
if ((config as any).globals['ts-jest'] && Object.keys((config as any).globals['ts-jest']).length === 0) {
225-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
226-
delete (config as any).globals['ts-jest']
227-
}
147+
delete config.globals['ts-jest']
228148
if (!Object.keys(config.globals).length) {
229149
delete config.globals
230150
}
@@ -240,7 +160,7 @@ function cleanupConfig(config: Config.InitialOptions): void {
240160
config.testMatch = dedupSort(config.testMatch)
241161
if (!config.testMatch.length) delete config.testMatch
242162
}
243-
if (config.preset === JestPresetNames.default) config.preset = defaults.name
163+
delete config.preset
244164
}
245165

246166
// eslint-disable-next-line @typescript-eslint/no-explicit-any

0 commit comments

Comments
 (0)
Please sign in to comment.