-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathtest-init.ts
263 lines (235 loc) · 7.75 KB
/
test-init.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
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
import * as path from "path";
import * as _ from "lodash";
import { TESTING_FRAMEWORKS, ProjectTypes } from "../constants";
import { fromWindowsRelativePathToUnix } from "../common/helpers";
import {
IProjectData,
ITestInitializationService,
} from "../definitions/project";
import { INodePackageManager, IOptions } from "../declarations";
import { IPluginsService } from "../definitions/plugins";
import { ICommand, ICommandParameter } from "../common/definitions/commands";
import {
IDictionary,
IErrors,
IFileSystem,
IResourceLoader,
IDependencyInformation,
} from "../common/declarations";
import { injector } from "../common/yok";
import { color } from "../color";
class TestInitCommand implements ICommand {
public allowedParameters: ICommandParameter[] = [];
private karmaConfigAdditionalFrameworks: IDictionary<string[]> = {
mocha: ["chai"],
};
constructor(
private $packageManager: INodePackageManager,
private $projectData: IProjectData,
private $errors: IErrors,
private $options: IOptions,
private $prompter: IPrompter,
private $fs: IFileSystem,
private $resources: IResourceLoader,
private $pluginsService: IPluginsService,
private $logger: ILogger,
private $testInitializationService: ITestInitializationService
) {
this.$projectData.initializeProjectData();
}
public async execute(args: string[]): Promise<void> {
const projectDir = this.$projectData.projectDir;
const frameworkToInstall =
this.$options.framework ||
(await this.$prompter.promptForChoice(
"Select testing framework:",
TESTING_FRAMEWORKS
));
if (TESTING_FRAMEWORKS.indexOf(frameworkToInstall) === -1) {
this.$errors.failWithHelp(
`Unknown or unsupported unit testing framework: ${frameworkToInstall}.`
);
}
const projectFilesExtension =
this.$projectData.projectType === ProjectTypes.TsFlavorName ||
this.$projectData.projectType === ProjectTypes.NgFlavorName
? ".ts"
: ".js";
let modulesToInstall: IDependencyInformation[] = [];
try {
modulesToInstall = this.$testInitializationService.getDependencies(
frameworkToInstall
);
} catch (err) {
this.$errors.fail(
`Unable to install the unit testing dependencies. Error: '${err.message}'`
);
}
modulesToInstall = modulesToInstall.filter(
(moduleToInstall) =>
!moduleToInstall.projectType ||
moduleToInstall.projectType === projectFilesExtension
);
for (const mod of modulesToInstall) {
let moduleToInstall = mod.name;
moduleToInstall += `@${mod.version}`;
await this.$packageManager.install(moduleToInstall, projectDir, {
"save-dev": true,
"save-exact": true,
optional: false,
disableNpmInstall: this.$options.disableNpmInstall,
frameworkPath: this.$options.frameworkPath,
ignoreScripts: this.$options.ignoreScripts,
path: this.$options.path,
});
const modulePath = path.join(projectDir, "node_modules", mod.name);
const modulePackageJsonPath = path.join(modulePath, "package.json");
const modulePackageJsonContent = this.$fs.readJson(modulePackageJsonPath);
const modulePeerDependencies =
modulePackageJsonContent.peerDependencies || {};
for (const peerDependency in modulePeerDependencies) {
const isPeerDependencyExcluded = _.includes(
mod.excludedPeerDependencies,
peerDependency
);
if (isPeerDependencyExcluded) {
continue;
}
const dependencyVersion = modulePeerDependencies[peerDependency] || "*";
// catch errors when a peerDependency is already installed
// e.g karma is installed; karma-jasmine depends on karma and will try to install it again
try {
await this.$packageManager.install(
`${peerDependency}@${dependencyVersion}`,
projectDir,
{
"save-dev": true,
"save-exact": true,
disableNpmInstall: false,
frameworkPath: this.$options.frameworkPath,
ignoreScripts: this.$options.ignoreScripts,
path: this.$options.path,
}
);
} catch (e) {
this.$logger.error(e.message);
}
}
}
await this.$pluginsService.add(
"@nativescript/unit-test-runner",
this.$projectData
);
this.$logger.clearScreen();
const bufferedLogs = [];
const testsDir = path.join(this.$projectData.appDirectoryPath, "tests");
const projectTestsDir = path.relative(
this.$projectData.projectDir,
testsDir
);
const relativeTestsDir = path.relative(
this.$projectData.appDirectoryPath,
testsDir
);
let shouldCreateSampleTests = true;
if (this.$fs.exists(testsDir)) {
const specFilenamePattern = `<filename>.spec${projectFilesExtension}`;
bufferedLogs.push(
color.yellow(
[
`Note: The "${projectTestsDir}" directory already exists, will not create example tests in the project.`,
`You may create "${specFilenamePattern}" files anywhere you'd like.`,
"",
].join("\n")
)
);
shouldCreateSampleTests = false;
}
this.$fs.ensureDirectoryExists(testsDir);
const frameworks = [frameworkToInstall]
.concat(this.karmaConfigAdditionalFrameworks[frameworkToInstall] || [])
.map((fw) => `'${fw}'`)
.join(", ");
const testFiles = `'${fromWindowsRelativePathToUnix(
relativeTestsDir
)}/**/*${projectFilesExtension}'`;
const karmaConfTemplate = this.$resources.readText("test/karma.conf.js");
const karmaConf = _.template(karmaConfTemplate)({
frameworks,
testFiles,
basePath: this.$projectData.getAppDirectoryRelativePath(),
});
this.$fs.writeFile(path.join(projectDir, "karma.conf.js"), karmaConf);
const exampleFilePath = this.$resources.resolvePath(
`test/example.${frameworkToInstall}${projectFilesExtension}`
);
const targetExampleTestPath = path.join(
testsDir,
`example.spec${projectFilesExtension}`
);
if (shouldCreateSampleTests && this.$fs.exists(exampleFilePath)) {
this.$fs.copyFile(exampleFilePath, targetExampleTestPath);
const targetExampleTestRelativePath = path.relative(
projectDir,
targetExampleTestPath
);
bufferedLogs.push(
`Added example test: ${color.yellow(targetExampleTestRelativePath)}`
);
}
// test main entry
const testMainResourcesPath = this.$resources.resolvePath(
`test/test-main${projectFilesExtension}`
);
const testMainPath = path.join(
this.$projectData.appDirectoryPath,
`test${projectFilesExtension}`
);
if (!this.$fs.exists(testMainPath)) {
this.$fs.copyFile(testMainResourcesPath, testMainPath);
const testMainRelativePath = path.relative(projectDir, testMainPath);
bufferedLogs.push(
`Main test entrypoint created: ${color.yellow(testMainRelativePath)}`
);
}
const testTsConfigTemplate = this.$resources.readText(
"test/tsconfig.spec.json"
);
const testTsConfig = _.template(testTsConfigTemplate)({
basePath: this.$projectData.getAppDirectoryRelativePath(),
});
this.$fs.writeFile(
path.join(projectDir, "tsconfig.spec.json"),
testTsConfig
);
bufferedLogs.push(`Added/replaced ${color.yellow("tsconfig.spec.json")}`);
const greyDollarSign = color.grey("$");
this.$logger.info(
[
[
color.green(`Tests using`),
color.cyan(frameworkToInstall),
color.green(`were successfully initialized.`),
].join(" "),
"",
...bufferedLogs,
"",
color.yellow(
`Note: @nativescript/unit-test-runner was included in "dependencies" as a convenience to automatically adjust your app's Info.plist on iOS and AndroidManifest.xml on Android to ensure the socket connects properly.`
),
"",
color.yellow(
`For production you may want to move to "devDependencies" and manage the settings yourself.`
),
"",
"",
`You can now run your tests:`,
"",
` ${greyDollarSign} ${color.green("ns test ios")}`,
` ${greyDollarSign} ${color.green("ns test android")}`,
"",
].join("\n")
);
}
}
injector.registerCommand("test|init", TestInitCommand);