Skip to content

Commit 68abcfb

Browse files
committedOct 6, 2018
fix(cli): change options to better reflect the new presets
1 parent 33ff29f commit 68abcfb

File tree

7 files changed

+134
-48
lines changed

7 files changed

+134
-48
lines changed
 

‎docs/user/config/stringifyContentPathRegex.md

+4-3
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,17 @@ In the `jest.config.js` version, you could do as in the `package.json` version o
1818

1919
```js
2020
// jest.config.js
21-
const { jestPreset } = require('ts-jest');
21+
// Here `defaults` can be replaced with any other preset
22+
const { defaults: tsjPreset } = require('ts-jest/presets');
2223

2324
module.exports = {
2425
// [...]
2526
moduleFileExtensions: [
26-
...jestPreset.moduleFileExtensions,
27+
...tsjPreset.moduleFileExtensions,
2728
'html'
2829
],
2930
transform: {
30-
...jestPreset.transform,
31+
...tsjPreset.transform,
3132
'\\.html$': 'ts-jest'
3233
}
3334
globals: {

‎docs/user/install.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ yarn ts-jest config:init
5555
This will create a basic Jest configuration file which will make Jest know about your `.ts` files and handle them correctly.
5656

5757
You can also use the `jest --init` command (prefixed with either `npx` or `yarn` depending on what you're using) to have more options related to Jest.
58-
However, answer `no` to the Jest question about whether or not to enable Typescript. Instead, add the line: `preset: "ts-jest"` to the the `jest.config.js` file afterwards.
58+
However, answer `no` to the Jest question about whether or not to enable Typescript. Instead, add the line: `preset: "ts-jest"` to the `jest.config.js` file afterwards.
5959

6060
### Customizing
6161

‎docs/user/react-native/index.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,13 @@ In the same way that you moved Babel config, move Jest config from `jest` key of
2525

2626
```js
2727
// jest.config.js
28-
const { jestPreset: tsJest } = require('ts-jest');
28+
const { defaults: tsjPreset } = require('ts-jest/presets');
2929

3030
module.exports = {
31-
...tsJest,
31+
...tsjPreset,
3232
preset: 'react-native',
3333
transform: {
34-
...tsJest.transform,
34+
...tsjPreset.transform,
3535
'\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js',
3636
},
3737
globals: {

‎src/cli/config/init.ts

+28-11
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { basename, join } from 'path'
1010
import { Arguments } from 'yargs'
1111

1212
import { CliCommand } from '..'
13-
import { createJestPreset } from '../../config/create-jest-preset'
13+
import { TsJestPresetDescriptor, defaults, jsWIthBabel, jsWithTs } from '../helpers/presets'
1414

1515
/**
1616
* @internal
@@ -24,12 +24,28 @@ export const run: CliCommand = async (args: Arguments /* , logger: Logger */) =>
2424
const pkgFile = isPackage ? filePath : join(process.cwd(), 'package.json')
2525
const hasPackage = isPackage || existsSync(pkgFile)
2626
// read config
27-
const { allowJs = false, jestPreset = true, tsconfig: askedTsconfig, babel = false, force, jsdom } = args
27+
const { jestPreset = true, tsconfig: askedTsconfig, force, jsdom } = args
2828
const tsconfig = askedTsconfig === 'tsconfig.json' ? undefined : askedTsconfig
29-
const hasPresetVar = allowJs || !jestPreset
3029
// read package
3130
const pkgJson = hasPackage ? JSON.parse(readFileSync(pkgFile, 'utf8')) : {}
3231

32+
// auto js/babel
33+
let { js, babel } = args
34+
if (js != null || babel != null) {
35+
if (js == null) js = babel ? 'babel' : undefined
36+
else if (babel == null) babel = js === 'babel'
37+
}
38+
39+
// preset
40+
let preset: TsJestPresetDescriptor | undefined
41+
if (js === 'babel') {
42+
preset = jsWIthBabel
43+
} else if (js === 'ts') {
44+
preset = jsWithTs
45+
} else {
46+
preset = defaults
47+
}
48+
3349
if (isPackage && !exists) {
3450
throw new Error(`File ${file} does not exists.`)
3551
} else if (!isPackage && exists && !force) {
@@ -52,7 +68,7 @@ export const run: CliCommand = async (args: Arguments /* , logger: Logger */) =>
5268

5369
if (isPackage) {
5470
// package.json config
55-
const base: any = hasPresetVar ? createJestPreset({ allowJs }) : { preset: 'ts-jest' }
71+
const base: any = jestPreset ? { preset: preset.name } : { ...preset.value }
5672
if (!jsdom) base.testEnvironment = 'node'
5773
if (tsconfig || babel) {
5874
const tsJestConf: any = {}
@@ -64,14 +80,14 @@ export const run: CliCommand = async (args: Arguments /* , logger: Logger */) =>
6480
} else {
6581
// js config
6682
const content = []
67-
if (hasPresetVar) {
68-
content.push(`const tsJest = require('ts-jest').createJestPreset({ allowJs: ${allowJs} });`, '')
83+
if (!jestPreset) {
84+
content.push(`${preset.jsImport('tsjPreset')};`, '')
6985
}
7086
content.push('module.exports = {')
71-
if (hasPresetVar) {
72-
content.push(` ...tsJest,`)
87+
if (jestPreset) {
88+
content.push(` preset: '${preset.name}',`)
7389
} else {
74-
content.push(` preset: 'ts-jest',`)
90+
content.push(` ...tsjPreset,`)
7591
}
7692
if (!jsdom) content.push(` testEnvironment: 'node',`)
7793

@@ -113,10 +129,11 @@ Arguments:
113129
114130
Options:
115131
--force Discard any existing Jest config
116-
--allow-js ts-jest will be used to process JS files as well
132+
--js ts|babel Process .js files with ts-jest if 'ts' or with
133+
babel-jest if 'babel'
117134
--no-jest-preset Disable the use of Jest presets
118135
--tsconfig <file> Path to the tsconfig.json file
119-
--babel Call BabelJest after ts-jest
136+
--babel Pipe babel-jest after ts-jest
120137
--jsdom Use jsdom as test environment instead of node
121138
`)
122139
}

‎src/cli/config/migrate.ts

+30-30
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,8 @@ import { basename, resolve } from 'path'
66
import { Arguments } from 'yargs'
77

88
import { CliCommand } from '..'
9-
import { TsJestPresets } from '../../config/create-jest-preset'
109
import { backportJestConfig } from '../../util/backports'
11-
12-
const DEFAULT_PRESET = 'ts-jest/presets/default'
10+
import { JestPresetNames, TsJestPresetDescriptor, allPresets, defaults } from '../helpers/presets'
1311

1412
/**
1513
* @internal
@@ -36,12 +34,14 @@ export const run: CliCommand = async (args: Arguments /*, logger: Logger*/) => {
3634
// migrate
3735
// first we backport our options
3836
const migratedConfig = backportJestConfig(nullLogger, actualConfig)
39-
let presetName: string | undefined
37+
let presetName: JestPresetNames | undefined
38+
let preset: TsJestPresetDescriptor | undefined
4039
// then we check if we can use `preset`
4140
if (!migratedConfig.preset && args.jestPreset) {
4241
// find the best preset
43-
if (args.allowJs) presetName = 'ts-jest/presets/js-with-ts'
44-
else {
42+
if (args.js) {
43+
presetName = args.js === 'babel' ? JestPresetNames.jsWIthBabel : JestPresetNames.jsWithTs
44+
} else {
4545
// try to detect what transformer the js extensions would target
4646
const jsTransformers = Object.keys(migratedConfig.transform || {}).reduce(
4747
(list, pattern) => {
@@ -59,49 +59,48 @@ export const run: CliCommand = async (args: Arguments /*, logger: Logger*/) => {
5959
const jsWithTs = jsTransformers.includes('ts-jest')
6060
const jsWithBabel = jsTransformers.includes('babel-jest')
6161
if (jsWithBabel && !jsWithTs) {
62-
presetName = 'ts-jest/presets/js-with-babel'
62+
presetName = JestPresetNames.jsWIthBabel
6363
} else if (jsWithTs && !jsWithBabel) {
64-
presetName = 'ts-jest/presets/js-with-ts'
64+
presetName = JestPresetNames.jsWithTs
6565
} else {
6666
// sounds like js files are NOT handled, or handled with a unknown transformer, so we do not need to handle it
67-
presetName = DEFAULT_PRESET
67+
presetName = JestPresetNames.default
6868
}
6969
}
7070
// ensure we are using a preset
71-
presetName = presetName || DEFAULT_PRESET
72-
migratedConfig.preset = presetName
71+
presetName = presetName || JestPresetNames.default
72+
preset = allPresets[presetName]
7373
footNotes.push(
74-
`Detected preset '${presetName.replace(
75-
/^ts-jest\/presets\//,
76-
'',
77-
)}' as the best matching preset for your configuration.\nVisit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more information about presets.\n`,
74+
`Detected preset '${preset.label}' as the best matching preset for your configuration.
75+
Visit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more information about presets.
76+
`,
7877
)
7978
} else if (migratedConfig.preset && migratedConfig.preset.startsWith('ts-jest')) {
8079
if (args.jestPreset === false) {
8180
delete migratedConfig.preset
8281
} else {
83-
presetName = migratedConfig.preset
82+
preset = (allPresets as any)[migratedConfig.preset] || defaults
8483
}
8584
}
86-
const presets: TsJestPresets | undefined = presetName
87-
? require(`../../../${presetName.replace(/^ts-jest\//, '')}/jest-preset`)
88-
: undefined
85+
86+
// enforce the correct name
87+
if (preset) migratedConfig.preset = preset.name
8988

9089
// check the extensions
91-
if (migratedConfig.moduleFileExtensions && migratedConfig.moduleFileExtensions.length && presets) {
92-
const presetValue = dedupSort(presets.moduleFileExtensions).join('::')
90+
if (migratedConfig.moduleFileExtensions && migratedConfig.moduleFileExtensions.length && preset) {
91+
const presetValue = dedupSort(preset.value.moduleFileExtensions).join('::')
9392
const migratedValue = dedupSort(migratedConfig.moduleFileExtensions).join('::')
9493
if (presetValue === migratedValue) {
9594
delete migratedConfig.moduleFileExtensions
9695
}
9796
}
9897
// there is a testRegex, remove our testMatch
99-
if (migratedConfig.testRegex && presets) {
98+
if (migratedConfig.testRegex && preset) {
10099
migratedConfig.testMatch = null as any
101100
}
102101
// check the testMatch
103-
else if (migratedConfig.testMatch && migratedConfig.testMatch.length && presets) {
104-
const presetValue = dedupSort(presets.testMatch).join('::')
102+
else if (migratedConfig.testMatch && migratedConfig.testMatch.length && preset) {
103+
const presetValue = dedupSort(preset.value.testMatch).join('::')
105104
const migratedValue = dedupSort(migratedConfig.testMatch).join('::')
106105
if (presetValue === migratedValue) {
107106
delete migratedConfig.testMatch
@@ -120,9 +119,9 @@ export const run: CliCommand = async (args: Arguments /*, logger: Logger*/) => {
120119
}
121120
// check if it's the same as the preset's one
122121
if (
123-
presets &&
122+
preset &&
124123
migratedConfig.transform &&
125-
stringifyJson(migratedConfig.transform) === stringifyJson(presets.transform)
124+
stringifyJson(migratedConfig.transform) === stringifyJson(preset.value.transform)
126125
) {
127126
delete migratedConfig.transform
128127
}
@@ -154,10 +153,10 @@ No migration needed for given Jest configuration
154153
// If it is the case, you can safely remove the "testMatch" from what I've migrated.
155154
// `)
156155
// }
157-
if (presets && migratedConfig.transform) {
156+
if (preset && migratedConfig.transform) {
158157
footNotes.push(`
159158
I couldn't check if your "transform" value is the same as mine which is: ${stringify(
160-
presets.transform,
159+
preset.value.transform,
161160
undefined,
162161
' ',
163162
)}
@@ -197,7 +196,7 @@ function cleanupConfig(config: jest.InitialOptions): void {
197196
config.testMatch = dedupSort(config.testMatch)
198197
if (config.testMatch.length === 0) delete config.testMatch
199198
}
200-
if (config.preset === DEFAULT_PRESET) config.preset = 'ts-jest'
199+
if (config.preset === JestPresetNames.default) config.preset = defaults.name
201200
}
202201

203202
function dedupSort(arr: any[]) {
@@ -220,7 +219,8 @@ Arguments:
220219
the "jest" property.
221220
222221
Options:
223-
--allow-js ts-jest will be used to process JS files as well
222+
--js ts|babel Process .js files with ts-jest if 'ts' or with
223+
babel-jest if 'babel'
224224
--no-jest-preset Disable the use of Jest presets
225225
`)
226226
}

‎src/cli/helpers/presets.ts

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { TsJestPresets } from '../../types'
2+
3+
/** @internal */
4+
export enum JestPresetNames {
5+
default = 'ts-jest/presets/default',
6+
jsWithTs = 'ts-jest/presets/js-with-ts',
7+
jsWIthBabel = 'ts-jest/presets/js-with-babel',
8+
}
9+
10+
/** @internal */
11+
export interface TsJestPresetDescriptor {
12+
name: string
13+
fullName: string
14+
label: string
15+
jsVarName: string
16+
value: TsJestPresets
17+
isDefault: boolean
18+
jsImport(varName?: string): string
19+
}
20+
21+
const definePreset = (fullName: string): TsJestPresetDescriptor => ({
22+
fullName,
23+
get name() {
24+
return this.isDefault ? 'ts-jest' : fullName
25+
},
26+
get label() {
27+
return fullName.split('/').pop()!
28+
},
29+
get jsVarName() {
30+
return this.isDefault
31+
? 'defaults'
32+
: fullName
33+
.split('/')
34+
.pop()!
35+
.replace(/\-([a-z])/g, (_, l) => l.toUpperCase())
36+
},
37+
get value() {
38+
return require(`../../../${fullName.replace(/^ts-jest\//, '')}/jest-preset`)
39+
},
40+
jsImport(varName = 'tsjPreset') {
41+
return `const { ${this.jsVarName}: ${varName} } = require('${this.fullName}')`
42+
},
43+
get isDefault() {
44+
return fullName === JestPresetNames.default
45+
},
46+
})
47+
48+
/** @internal */
49+
export const allPresets: Record<JestPresetNames, TsJestPresetDescriptor> = {} as any
50+
/** @internal */
51+
export const defaults = (allPresets[JestPresetNames.default] = definePreset(JestPresetNames.default))
52+
/** @internal */
53+
export const jsWithTs = (allPresets[JestPresetNames.jsWithTs] = definePreset(JestPresetNames.jsWithTs))
54+
/** @internal */
55+
export const jsWIthBabel = (allPresets[JestPresetNames.jsWIthBabel] = definePreset(JestPresetNames.jsWIthBabel))

‎src/cli/index.ts

+13
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,21 @@ async function cli(args: string[]): Promise<void> {
2020
count: ['verbose'],
2121
alias: { verbose: ['v'] },
2222
default: { jestPreset: true, verbose: 0 },
23+
coerce: {
24+
js(val: string) {
25+
const res = val.trim().toLowerCase()
26+
if (!['babel', 'ts'].includes(res)) throw new Error(`The 'js' option must be 'babel' or 'ts', given: '${val}'.`)
27+
return res
28+
},
29+
},
2330
})
2431

32+
// deprecated
33+
if (parsedArgv.allowJs != null) {
34+
if (parsedArgv.js) throw new Error(`The 'allowJs' and 'js' options cannot be set together.`)
35+
parsedArgv.js = parsedArgv.allowJs ? 'ts' : undefined
36+
}
37+
2538
let command = parsedArgv._.shift() as string
2639
const isHelp = command === 'help'
2740
if (isHelp) command = parsedArgv._.shift() as string

0 commit comments

Comments
 (0)
Please sign in to comment.