0
# Generator Testing Helpers
1
2
The YeomanTest class provides utility functions for creating, mocking, and managing generators and test environments. It supports dummy generators, mocked interactions, environment configuration, and both functional and class-based testing approaches.
3
4
## Capabilities
5
6
### Helper Instance Creation
7
8
Create customized helper instances with specific configurations.
9
10
```typescript { .api }
11
/**
12
* Create a customized YeomanTest instance with specific options
13
* @param options - Configuration options to apply to the helper instance
14
* @returns New YeomanTest instance with applied options
15
*/
16
function createHelpers(options: Partial<YeomanTest>): YeomanTest;
17
18
/**
19
* Default YeomanTest instance available as default export
20
*/
21
const defaultHelpers: YeomanTest;
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
import { createHelpers } from "yeoman-test";
28
29
// Create helper with custom settings
30
const helpers = createHelpers({
31
settings: { tmpdir: false },
32
environmentOptions: { localConfigOnly: false },
33
generatorOptions: { skipInstall: true }
34
});
35
36
// Use custom helper
37
await helpers.run("my-generator");
38
```
39
40
### Generator Creation
41
42
Create generator instances with dependencies and configuration for testing.
43
44
```typescript { .api }
45
/**
46
* Create a generator instance with dependencies and options
47
* @param name - Generator name or constructor
48
* @param options - Configuration including dependencies and instantiation options
49
* @returns Promise resolving to generator instance
50
*/
51
async createGenerator<GeneratorType extends BaseGenerator = DefaultGeneratorApi>(
52
name: string | GetGeneratorConstructor<GeneratorType>,
53
options?: {
54
dependencies?: Dependency[];
55
localConfigOnly?: boolean;
56
} & InstantiateOptions<GeneratorType>
57
): Promise<GeneratorType>;
58
59
type Dependency = string | Parameters<DefaultEnvironmentApi['register']>;
60
```
61
62
**Usage Examples:**
63
64
```typescript
65
import helpers from "yeoman-test";
66
67
// Create generator with dependencies
68
const generator = await helpers.createGenerator("my-generator", {
69
dependencies: [
70
"./path/to/dep-generator",
71
["./other-generator", { namespace: "other:gen" }]
72
],
73
localConfigOnly: true,
74
generatorArgs: ["init"],
75
generatorOptions: { force: true }
76
});
77
78
// Use the generator instance
79
await generator.run();
80
```
81
82
### Dummy Generator Creation
83
84
Create simple, customizable generators for testing scenarios.
85
86
```typescript { .api }
87
/**
88
* Create a simple, dummy generator for testing
89
* @param Generator - Base generator class (defaults to yeoman-generator)
90
* @param contents - Object defining methods and properties for the dummy generator
91
* @returns Generator constructor that can be instantiated
92
*/
93
createDummyGenerator<GenParameter extends BaseGenerator = DefaultGeneratorApi>(
94
Generator?: GetGeneratorConstructor<GenParameter>,
95
contents?: Record<string, (...args: any[]) => void>
96
): new (...args: any[]) => GenParameter;
97
```
98
99
**Usage Examples:**
100
101
```typescript
102
import helpers from "yeoman-test";
103
104
// Basic dummy generator
105
const DummyGen = helpers.createDummyGenerator();
106
107
// Custom dummy generator with methods
108
const CustomDummyGen = helpers.createDummyGenerator(undefined, {
109
writing(this: any) {
110
this.fs.write("output.txt", "Hello World");
111
},
112
113
install(this: any) {
114
this.spawnCommand("npm", ["install"]);
115
}
116
});
117
118
// Use in tests
119
await helpers.run(CustomDummyGen)
120
.withSpawnMock();
121
122
result.assertFile("output.txt");
123
```
124
125
### Mocked Generator Creation
126
127
Create fully mocked generators for testing generator composition.
128
129
```typescript { .api }
130
/**
131
* Create a mocked generator with stubbed methods
132
* @param GeneratorClass - Base generator class to mock
133
* @returns Mocked generator constructor with stubbed methods
134
*/
135
createMockedGenerator(GeneratorClass?: any): ReturnType<typeof mock.fn>;
136
```
137
138
**Usage Examples:**
139
140
```typescript
141
import helpers from "yeoman-test";
142
143
// Create mocked generator
144
const MockedGen = helpers.createMockedGenerator();
145
146
// Use in test environment
147
const env = await helpers.createTestEnv();
148
env.register(MockedGen, { namespace: "mocked:gen" });
149
150
// Verify mock was called
151
expect(MockedGen.mock.callCount()).toBeGreaterThan(0);
152
```
153
154
### Legacy Helper Methods (Deprecated)
155
156
Legacy methods maintained for backward compatibility.
157
158
```typescript { .api }
159
/**
160
* @deprecated Use inTmpDir from RunContext instead
161
* Create a function that will clean up the test directory
162
* @param dir - Path to the test directory
163
* @returns Mocha callback function
164
*/
165
setUpTestDirectory(dir: string): () => void;
166
167
/**
168
* @deprecated Use inTmpDir from RunContext instead
169
* Clean-up the test directory and cd into it
170
* @param dir - Path to the test directory
171
* @param cb - Callback executed after setting working directory
172
*/
173
testDirectory(dir: string, callback?: (error?: any) => unknown): void;
174
175
/**
176
* @deprecated Use withAnswers from RunContext instead
177
* Answer prompt questions for the passed-in generator
178
* @param generator - Yeoman generator or environment
179
* @param answers - Object mapping prompt names to answers
180
* @param options - Prompt options
181
*/
182
mockPrompt(
183
environmentOrGenerator: BaseGenerator | DefaultEnvironmentApi,
184
mockedAnswers?: PromptAnswers,
185
options?: DummyPromptOptions
186
): void;
187
188
/**
189
* @deprecated Use test cleanup methods instead
190
* Restore defaults prompts on a generator
191
* @param generator - Generator or environment instance
192
*/
193
restorePrompt(environmentOrGenerator: BaseGenerator | DefaultEnvironmentApi): void;
194
195
/**
196
* @deprecated Use withLocalConfig from RunContext instead
197
* Provide mocked values to the config
198
* @param generator - Yeoman generator instance
199
* @param localConfig - Configuration object
200
*/
201
mockLocalConfig(generator: BaseGenerator, localConfig: any): void;
202
```
203
204
## YeomanTest Class Configuration
205
206
The YeomanTest class can be configured with default settings that apply to all test contexts created from that instance.
207
208
### Instance Properties
209
210
```typescript { .api }
211
class YeomanTest {
212
/** Default settings for RunContext creation */
213
settings?: RunContextSettings;
214
215
/** Default environment options */
216
environmentOptions?: BaseEnvironmentOptions;
217
218
/** Default generator options */
219
generatorOptions?: BaseGeneratorOptions;
220
221
/** Default adapter options */
222
adapterOptions?: Omit<TestAdapterOptions, 'mockedAnswers'>;
223
}
224
```
225
226
**Usage Examples:**
227
228
```typescript
229
import { createHelpers } from "yeoman-test";
230
231
// Create configured helper instance
232
const helpers = createHelpers({
233
settings: {
234
tmpdir: true,
235
autoCleanup: true
236
},
237
environmentOptions: {
238
localConfigOnly: true,
239
skipCache: true
240
},
241
generatorOptions: {
242
skipInstall: true,
243
force: true
244
}
245
});
246
247
// All run contexts from this helper will use these defaults
248
await helpers.run("my-generator"); // Uses configured defaults
249
```
250
251
### Method Override Pattern
252
253
YeomanTest methods can be overridden for custom behavior:
254
255
```typescript { .api }
256
/**
257
* Get RunContext constructor - can be overridden for custom context types
258
* @returns RunContext constructor function
259
*/
260
getRunContextType(): typeof RunContext;
261
```
262
263
**Usage Examples:**
264
265
```typescript
266
import { createHelpers, RunContext } from "yeoman-test";
267
268
// Custom RunContext with additional methods
269
class CustomRunContext extends RunContext {
270
withCustomFeature() {
271
// Add custom functionality
272
return this;
273
}
274
}
275
276
// Create helper with custom context type
277
const helpers = createHelpers({});
278
helpers.getRunContextType = () => CustomRunContext;
279
280
// Now all contexts will be CustomRunContext instances
281
const context = helpers.run("my-generator") as CustomRunContext;
282
context.withCustomFeature();
283
```
284
285
## Advanced Usage Patterns
286
287
### Generator Factory Pattern
288
289
```typescript
290
// Create reusable generator factory
291
function createTestGenerator(options = {}) {
292
return helpers.createDummyGenerator(undefined, {
293
writing(this: any) {
294
this.fs.writeJSON("package.json", {
295
name: options.name || "test-app",
296
version: options.version || "1.0.0"
297
});
298
}
299
});
300
}
301
302
// Use in multiple tests
303
const TestGen = createTestGenerator({ name: "my-app" });
304
await helpers.run(TestGen);
305
```
306
307
### Composition Testing Pattern
308
309
```typescript
310
// Test generator that composes with others
311
await helpers.run("main-generator")
312
.withMockedGenerators([
313
"sub:component",
314
"sub:service",
315
"common:utils"
316
]);
317
318
// Verify composition behavior
319
result.assertGeneratorComposed("sub:component");
320
result.assertGeneratorComposedOnce("common:utils");
321
322
const composedGens = result.getComposedGenerators();
323
expect(composedGens).toHaveLength(2);
324
```
325
326
### Multi-Stage Testing Pattern
327
328
```typescript
329
// Run initial generator
330
await helpers.run("init-generator")
331
.withAnswers({ projectType: "library" });
332
333
// Run follow-up generator in same directory
334
await result.create("feature-generator")
335
.withAnswers({ featureName: "auth" })
336
.withLocalConfig({ initialized: true });
337
338
// Verify combined result
339
result.assertFile(["package.json", "src/auth.ts"]);
340
```