0
# Configuration Management
1
2
Utilities for programmatically modifying Jest configuration files using AST-based manipulation. These functions provide safe, type-aware methods for updating Jest configurations without manual string manipulation.
3
4
## Capabilities
5
6
### Config Property Management
7
8
Add or remove properties from Jest configuration files with full TypeScript AST support.
9
10
```typescript { .api }
11
/**
12
* Add a property to the Jest configuration file
13
* @param host - Nx virtual file system tree
14
* @param path - Path to Jest configuration file
15
* @param propertyName - Property name or nested path (e.g., 'transform' or ['setupFilesAfterEnv', 0])
16
* @param value - Value to set for the property
17
* @param options - Configuration options for value handling
18
*/
19
function addPropertyToJestConfig(
20
host: Tree,
21
path: string,
22
propertyName: string | string[],
23
value: unknown,
24
options?: { valueAsString: boolean }
25
): void;
26
27
/**
28
* Remove a property from the Jest configuration file
29
* @param host - Nx virtual file system tree
30
* @param path - Path to Jest configuration file
31
* @param propertyName - Property name or nested path to remove
32
*/
33
function removePropertyFromJestConfig(
34
host: Tree,
35
path: string,
36
propertyName: string | string[]
37
): void;
38
```
39
40
**Usage Examples:**
41
42
```typescript
43
import { addPropertyToJestConfig, removePropertyFromJestConfig } from "@nx/jest";
44
import { Tree } from '@nx/devkit';
45
46
// Add a simple property
47
addPropertyToJestConfig(
48
tree,
49
"apps/my-app/jest.config.ts",
50
"verbose",
51
true
52
);
53
54
// Add nested configuration
55
addPropertyToJestConfig(
56
tree,
57
"apps/my-app/jest.config.ts",
58
["transform", "^.+\\.vue$"],
59
"vue-jest"
60
);
61
62
// Add array element
63
addPropertyToJestConfig(
64
tree,
65
"apps/my-app/jest.config.ts",
66
["setupFilesAfterEnv", 0],
67
"<rootDir>/src/test-setup.ts"
68
);
69
70
// Add raw code as string
71
addPropertyToJestConfig(
72
tree,
73
"apps/my-app/jest.config.ts",
74
"testMatch",
75
"['<rootDir>/src/**/*.spec.ts']",
76
{ valueAsString: true }
77
);
78
79
// Remove properties
80
removePropertyFromJestConfig(
81
tree,
82
"apps/my-app/jest.config.ts",
83
"verbose"
84
);
85
86
// Remove nested property
87
removePropertyFromJestConfig(
88
tree,
89
"apps/my-app/jest.config.ts",
90
["moduleNameMapper", "^@/(.*)$"]
91
);
92
```
93
94
### AST Configuration Parsing
95
96
Parse Jest configuration files as TypeScript AST objects for advanced manipulation.
97
98
```typescript { .api }
99
/**
100
* Parse Jest configuration file content into a TypeScript AST object
101
* @param configString - Raw content of Jest configuration file
102
* @returns TypeScript ObjectLiteralExpression AST node
103
*/
104
function jestConfigObjectAst(configString: string): ts.ObjectLiteralExpression;
105
106
/**
107
* Get Jest configuration object from file content
108
* @param host - Nx virtual file system tree
109
* @param path - Path to Jest configuration file
110
* @returns Parsed Jest configuration object
111
*/
112
function jestConfigObject(
113
host: Tree,
114
path: string
115
): Partial<Config.InitialOptions> & { [index: string]: any };
116
117
/**
118
* Add import statement to Jest configuration file
119
* @param host - Nx virtual file system tree
120
* @param path - Path to Jest configuration file
121
* @param importStatement - Import statement to add at the top of the file
122
*/
123
function addImportStatementToJestConfig(
124
host: Tree,
125
path: string,
126
importStatement: string
127
): void;
128
```
129
130
**Usage Examples:**
131
132
```typescript
133
import { jestConfigObjectAst, jestConfigObject, addImportStatementToJestConfig } from "@nx/jest";
134
135
// Parse configuration as AST
136
const configContent = tree.read("jest.config.ts", "utf-8");
137
const configAst = jestConfigObjectAst(configContent);
138
139
// Now you can manipulate the AST directly
140
console.log(configAst.properties.length); // Number of configuration properties
141
142
// Get configuration as JavaScript object
143
const configObject = jestConfigObject(tree, "jest.config.ts");
144
console.log(configObject.testEnvironment); // Access configuration values
145
146
// Add import statement to configuration file
147
addImportStatementToJestConfig(
148
tree,
149
"jest.config.ts",
150
"import { customMatcher } from './test-utils';"
151
);
152
```
153
154
### Advanced AST Manipulation
155
156
Low-level functions for direct AST manipulation of Jest configuration objects.
157
158
```typescript { .api }
159
/**
160
* Add or update a property in a TypeScript object literal AST
161
* @param tree - Nx virtual file system tree
162
* @param object - TypeScript ObjectLiteralExpression to modify
163
* @param properties - Array of property names for nested access
164
* @param value - Value to set (as string representation)
165
* @param path - File path for error reporting
166
*/
167
function addOrUpdateProperty(
168
tree: Tree,
169
object: ts.ObjectLiteralExpression,
170
properties: string[],
171
value: unknown,
172
path: string
173
): void;
174
175
/**
176
* Remove a property from a TypeScript object literal AST
177
* @param tree - Nx virtual file system tree
178
* @param object - TypeScript ObjectLiteralExpression to modify
179
* @param properties - Array of property names for nested access
180
* @param path - File path for error reporting
181
*/
182
function removeProperty(
183
tree: Tree,
184
object: ts.ObjectLiteralExpression,
185
properties: string[],
186
path: string
187
): void;
188
```
189
190
**Usage Examples:**
191
192
```typescript
193
import { addOrUpdateProperty, removeProperty, jestConfigObjectAst } from "@nx/jest";
194
195
const configContent = tree.read("jest.config.ts", "utf-8");
196
const configObject = jestConfigObjectAst(configContent);
197
198
// Add nested property
199
addOrUpdateProperty(
200
tree,
201
configObject,
202
["coverageThreshold", "global", "branches"],
203
"80",
204
"jest.config.ts"
205
);
206
207
// Remove nested property
208
removeProperty(
209
tree,
210
configObject,
211
["transform", "^.+\\.jsx?$"],
212
"jest.config.ts"
213
);
214
```
215
216
### Common Configuration Patterns
217
218
#### Adding Test Environment Configuration
219
220
```typescript
221
// Set test environment
222
addPropertyToJestConfig(tree, configPath, "testEnvironment", "jsdom");
223
224
// Add test environment options
225
addPropertyToJestConfig(
226
tree,
227
configPath,
228
"testEnvironmentOptions",
229
{
230
customExportConditions: ["node", "require"]
231
}
232
);
233
```
234
235
#### Configuring Module Resolution
236
237
```typescript
238
// Add module name mapper
239
addPropertyToJestConfig(
240
tree,
241
configPath,
242
["moduleNameMapper", "^@/(.*)$"],
243
"<rootDir>/src/$1"
244
);
245
246
// Add module file extensions
247
addPropertyToJestConfig(
248
tree,
249
configPath,
250
"moduleFileExtensions",
251
["ts", "tsx", "js", "jsx", "json"]
252
);
253
```
254
255
#### Setting Up Transformations
256
257
```typescript
258
// Add TypeScript transformation
259
addPropertyToJestConfig(
260
tree,
261
configPath,
262
["transform", "^.+\\.ts$"],
263
["ts-jest", { tsconfig: "<rootDir>/tsconfig.spec.json" }]
264
);
265
266
// Add file transformation for assets
267
addPropertyToJestConfig(
268
tree,
269
configPath,
270
["transform", "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)$"],
271
"jest-transform-stub"
272
);
273
```
274
275
#### Coverage Configuration
276
277
```typescript
278
// Set coverage directory
279
addPropertyToJestConfig(
280
tree,
281
configPath,
282
"coverageDirectory",
283
"coverage"
284
);
285
286
// Configure coverage reporters
287
addPropertyToJestConfig(
288
tree,
289
configPath,
290
"coverageReporters",
291
["html", "text", "lcov"]
292
);
293
294
// Set coverage thresholds
295
addPropertyToJestConfig(
296
tree,
297
configPath,
298
"coverageThreshold",
299
{
300
global: {
301
branches: 80,
302
functions: 80,
303
lines: 80,
304
statements: 80
305
}
306
}
307
);
308
```
309
310
### Error Handling
311
312
The configuration management functions include built-in error handling:
313
314
- **File Not Found**: Throws error if Jest configuration file doesn't exist
315
- **Parse Errors**: Logs warnings and manual update instructions for invalid syntax
316
- **AST Manipulation Errors**: Provides detailed error messages for failed property operations
317
318
```typescript
319
try {
320
addPropertyToJestConfig(tree, "invalid/path.ts", "testMatch", ["**/*.spec.ts"]);
321
} catch (error) {
322
console.error("Failed to update Jest config:", error.message);
323
// Error: Cannot find 'invalid/path.ts' in your workspace.
324
}
325
```
326
327
### Property Name Formats
328
329
Property names can be specified in multiple formats:
330
331
```typescript
332
// Simple property name
333
addPropertyToJestConfig(tree, path, "verbose", true);
334
335
// Dot-separated nested properties
336
addPropertyToJestConfig(tree, path, "coverageThreshold.global.branches", 80);
337
338
// Array of property names for complex nesting
339
addPropertyToJestConfig(tree, path, ["transform", "^.+\\.vue$"], "vue-jest");
340
341
// Array indices for array properties
342
addPropertyToJestConfig(tree, path, ["setupFilesAfterEnv", 0], "./setup.ts");
343
```