/
index.ts
150 lines (126 loc) · 3.83 KB
/
index.ts
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
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as fs from 'fs';
import * as path from 'path';
import chalk = require('chalk');
import prompts = require('prompts');
import {sync as realpath} from 'realpath-native';
import {constants} from 'jest-config';
import defaultQuestions, {testScriptQuestion} from './questions';
import {MalformedPackageJsonError, NotFoundPackageJsonError} from './errors';
import generateConfigFile from './generate_config_file';
import modifyPackageJson from './modify_package_json';
import {ProjectPackageJson} from './types';
const {
JEST_CONFIG_BASE_NAME,
JEST_CONFIG_EXT_MJS,
JEST_CONFIG_EXT_JS,
JEST_CONFIG_EXT_ORDER,
PACKAGE_JSON,
} = constants;
type PromptsResults = {
clearMocks: boolean;
coverage: boolean;
environment: boolean;
scripts: boolean;
};
const getConfigFilename = (ext: string) => JEST_CONFIG_BASE_NAME + ext;
export default async (
rootDir: string = realpath(process.cwd()),
): Promise<void> => {
// prerequisite checks
const projectPackageJsonPath: string = path.join(rootDir, PACKAGE_JSON);
if (!fs.existsSync(projectPackageJsonPath)) {
throw new NotFoundPackageJsonError(rootDir);
}
const questions = defaultQuestions.slice(0);
let hasJestProperty: boolean = false;
let projectPackageJson: ProjectPackageJson;
try {
projectPackageJson = JSON.parse(
fs.readFileSync(projectPackageJsonPath, 'utf-8'),
);
} catch (error) {
throw new MalformedPackageJsonError(projectPackageJsonPath);
}
if (projectPackageJson.jest) {
hasJestProperty = true;
}
const existingJestConfigPath = JEST_CONFIG_EXT_ORDER.find(ext =>
fs.existsSync(path.join(rootDir, getConfigFilename(ext))),
);
const jestConfigPath =
existingJestConfigPath ||
path.join(
rootDir,
getConfigFilename(
projectPackageJson.type === 'module'
? JEST_CONFIG_EXT_MJS
: JEST_CONFIG_EXT_JS,
),
);
if (hasJestProperty || existingJestConfigPath) {
const result: {continue: boolean} = await prompts({
initial: true,
message:
'It seems that you already have a jest configuration, do you want to override it?',
name: 'continue',
type: 'confirm',
});
if (!result.continue) {
console.log();
console.log('Aborting...');
return;
}
}
// Add test script installation only if needed
if (
!projectPackageJson.scripts ||
projectPackageJson.scripts.test !== 'jest'
) {
questions.unshift(testScriptQuestion);
}
// Start the init process
console.log();
console.log(
chalk.underline(
`The following questions will help Jest to create a suitable configuration for your project\n`,
),
);
let promptAborted: boolean = false;
// @ts-ignore: Return type cannot be object - faulty typings
const results: PromptsResults = await prompts(questions, {
onCancel: () => {
promptAborted = true;
},
});
if (promptAborted) {
console.log();
console.log('Aborting...');
return;
}
const shouldModifyScripts = results.scripts;
if (shouldModifyScripts || hasJestProperty) {
const modifiedPackageJson = modifyPackageJson({
projectPackageJson,
shouldModifyScripts,
});
fs.writeFileSync(projectPackageJsonPath, modifiedPackageJson);
console.log('');
console.log(`✏️ Modified ${chalk.cyan(projectPackageJsonPath)}`);
}
const generatedConfig = generateConfigFile(
results,
projectPackageJson.type === 'module' ||
jestConfigPath.endsWith(JEST_CONFIG_EXT_MJS),
);
fs.writeFileSync(jestConfigPath, generatedConfig);
console.log('');
console.log(
`📝 Configuration file created at ${chalk.cyan(jestConfigPath)}`,
);
};