or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

generator-helpers.mdindex.mdrun-context.mdrun-result.mdtest-adapter.mdtest-environment.md

index.mddocs/

0

# Yeoman Test

1

2

Yeoman Test provides comprehensive test utilities specifically designed for testing Yeoman generators. It offers a fluent, chainable API through RunContext for setting up test environments with customizable options, temporary directories, mocked generators, file system states, and simulated user inputs. The library includes powerful assertion methods through RunResult for verifying file creation, content validation, JSON structure testing, and generator behavior verification.

3

4

## Package Information

5

6

- **Package Name**: yeoman-test

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install --save-dev yeoman-test`

10

11

**Peer Dependencies:**

12

```bash

13

npm install --save-dev yeoman-generator@xxx yeoman-environment@xxx

14

```

15

16

## Core Imports

17

18

```typescript

19

import helpers, { result } from "yeoman-test";

20

```

21

22

For specific components:

23

24

```typescript

25

import {

26

YeomanTest,

27

RunContext,

28

RunContextBase,

29

RunResult,

30

TestAdapter,

31

createHelpers,

32

context,

33

result

34

} from "yeoman-test";

35

```

36

37

CommonJS:

38

39

```javascript

40

const helpers = require("yeoman-test");

41

const { result, context, TestAdapter } = require("yeoman-test");

42

```

43

44

## Basic Usage

45

46

**Simple Generator Test:**

47

48

```typescript

49

import helpers, { result } from "yeoman-test";

50

51

describe("my-generator", () => {

52

beforeEach(async () => {

53

await helpers

54

.run("my-generator") // Generator namespace or path

55

.withOptions({ skipInstall: true })

56

.withAnswers({ projectName: "test-app" });

57

});

58

59

it("creates expected files", () => {

60

result.assertFile("package.json");

61

result.assertFileContent("package.json", '"name": "test-app"');

62

});

63

});

64

```

65

66

**Advanced Test Configuration:**

67

68

```typescript

69

import helpers, { result } from "yeoman-test";

70

71

describe("complex generator test", () => {

72

beforeEach(async () => {

73

await helpers

74

.run("my-generator")

75

.withFiles({

76

"existing.json": '{ "config": true }',

77

"templates/base.hbs": "Hello {{name}}"

78

})

79

.withYoRcConfig("my-generator", { theme: "dark" })

80

.withMockedGenerators(["sub-generator"])

81

.withSpawnMock();

82

});

83

84

it("composes with sub-generator", () => {

85

result.assertGeneratorComposed("sub-generator");

86

});

87

});

88

```

89

90

## Architecture

91

92

Yeoman Test is built around several key components:

93

94

- **RunContext**: Fluent API for configuring and executing generator tests with chainable methods

95

- **RunResult**: Comprehensive assertion utilities for verifying file system changes and generator behavior

96

- **TestAdapter**: Mock adapter that simulates user prompts and interactions

97

- **YeomanTest**: Helper class containing utility methods for creating test environments and generators

98

- **Memory File System**: Isolated file system operations using mem-fs for safe testing without affecting real files

99

100

## Capabilities

101

102

### Test Execution Context

103

104

Core functionality for setting up and executing generator tests with a fluent, chainable API that supports configuration, mocking, and lifecycle management.

105

106

```typescript { .api }

107

function run<GeneratorType extends BaseGenerator = DefaultGeneratorApi>(

108

GeneratorOrNamespace: string | GetGeneratorConstructor<GeneratorType>,

109

settings?: RunContextSettings,

110

environmentOptions?: BaseEnvironmentOptions

111

): RunContext<GeneratorType>;

112

113

function create<GeneratorType extends BaseGenerator = DefaultGeneratorApi>(

114

GeneratorOrNamespace: string | GetGeneratorConstructor<GeneratorType>,

115

settings?: RunContextSettings,

116

environmentOptions?: BaseEnvironmentOptions

117

): RunContext<GeneratorType>;

118

119

function prepareTemporaryDir(settings?: RunContextSettings): BasicRunContext;

120

121

interface RunContextSettings {

122

tmpdir?: boolean;

123

cwd?: string;

124

forwardCwd?: boolean;

125

autoCleanup?: boolean;

126

memFs?: Store<MemFsEditorFile>;

127

resolved?: string;

128

namespace?: string;

129

}

130

```

131

132

[Test Execution Context](./run-context.md)

133

134

### Test Result Assertions

135

136

Comprehensive assertion utilities for verifying file creation, content validation, JSON structure testing, and generator behavior with support for both individual and batch operations.

137

138

```typescript { .api }

139

class RunResult<GeneratorType extends BaseGenerator = BaseGenerator> {

140

assertFile(path: string | string[]): void;

141

assertFileContent(file: string, reg: string | RegExp): void;

142

assertJsonFileContent(filename: string, content: Record<string, any>): void;

143

assertGeneratorComposed(generator: string): void;

144

getSnapshot(filter?: Function): Record<string, { contents: string; stateCleared: string }>;

145

}

146

```

147

148

[Test Result Assertions](./run-result.md)

149

150

### Generator Testing Helpers

151

152

Utility functions for creating, mocking, and managing generators and test environments with support for dummy generators, mocked interactions, and environment configuration.

153

154

```typescript { .api }

155

class YeomanTest {

156

createGenerator<GeneratorType>(name: string, options?: {

157

dependencies?: Dependency[];

158

localConfigOnly?: boolean;

159

}): Promise<GeneratorType>;

160

161

createDummyGenerator<GenParameter>(

162

Generator?: GetGeneratorConstructor<GenParameter>,

163

contents?: Record<string, Function>

164

): new (...args: any[]) => GenParameter;

165

166

createMockedGenerator(GeneratorClass?: any): ReturnType<typeof mock.fn>;

167

}

168

169

type Dependency = string | Parameters<DefaultEnvironmentApi['register']>;

170

```

171

172

[Generator Testing Helpers](./generator-helpers.md)

173

174

### Test Environment Setup

175

176

Functionality for creating and configuring Yeoman test environments with custom adapters, shared file systems, and environment-specific options.

177

178

```typescript { .api }

179

class YeomanTest {

180

createEnv(options: BaseEnvironmentOptions): Promise<DefaultEnvironmentApi>;

181

182

createTestEnv(

183

environmentContructor?: CreateEnv,

184

options?: BaseEnvironmentOptions

185

): Promise<DefaultEnvironmentApi>;

186

187

createTestAdapter(options?: TestAdapterOptions): TestAdapter;

188

}

189

190

type CreateEnv = (options: BaseEnvironmentOptions) => Promise<BaseEnvironment>;

191

```

192

193

[Test Environment Setup](./test-environment.md)

194

195

### Test Adapter

196

197

Mock adapter for simulating user prompts and interactions with full control over question responses and prompt behavior.

198

199

```typescript { .api }

200

class TestAdapter {

201

constructor(options?: TestAdapterOptions);

202

203

// Inherits from @yeoman/adapter TestAdapter

204

prompt<T extends PromptAnswers = PromptAnswers>(

205

questions: PromptQuestions<T>

206

): Promise<T>;

207

}

208

209

interface TestAdapterOptions {

210

mockedAnswers?: PromptAnswers;

211

callback?: DummyPromptCallback;

212

}

213

214

type DummyPromptCallback = (prompt: any) => any;

215

```

216

217

[Test Adapter](./test-adapter.md)

218

219

### Mocha Integration

220

221

Specialized hooks and utilities for seamless integration with Mocha test framework, providing automatic cleanup and context management.

222

223

```typescript { .api }

224

export const mochaHooks: {

225

afterAll(): void;

226

};

227

228

// Import as:

229

import "yeoman-test/mocha-cleanup";

230

```

231

232

The mocha-cleanup export provides automatic test cleanup when used with Mocha's global hooks feature.

233

234

### Global Test Context

235

236

Global context and result instances for simplified test access and state management.

237

238

```typescript { .api }

239

// Global test context with manual control

240

const context: {

241

startNewContext(): void;

242

};

243

244

// Global result proxy for accessing the last RunResult

245

const result: RunResult;

246

```

247

248

**Usage Examples:**

249

250

```typescript

251

import { context, result } from "yeoman-test";

252

253

describe("sequential tests", () => {

254

beforeEach(() => {

255

context.startNewContext(); // Start fresh context

256

});

257

258

it("can access results globally", async () => {

259

await helpers.run("my-generator");

260

// result automatically refers to the last execution

261

result.assertFile("package.json");

262

});

263

});

264

```

265

266

## Types

267

268

```typescript { .api }

269

interface RunContextSettings {

270

/** Automatically run this generator in a tmp dir (default: true) */

271

tmpdir?: boolean;

272

/** Working directory for the test */

273

cwd?: string;

274

/** Original working directory before test */

275

oldCwd?: string;

276

/** Forward cwd to environment */

277

forwardCwd?: boolean;

278

/** Automatically cleanup after test */

279

autoCleanup?: boolean;

280

/** Memory file system instance */

281

memFs?: Store<MemFsEditorFile>;

282

/** File path to the generator (only used if Generator is a constructor) */

283

resolved?: string;

284

/** Namespace (only used if Generator is a constructor, default: 'gen:test') */

285

namespace?: string;

286

}

287

288

interface RunResultOptions<GeneratorType extends BaseGenerator> {

289

generator: GeneratorType;

290

env: DefaultEnvironmentApi;

291

envOptions: BaseEnvironmentOptions;

292

cwd: string;

293

oldCwd: string;

294

memFs: Store<MemFsEditorFile>;

295

mockedGenerators: Record<string, BaseGenerator>;

296

spawnStub?: any;

297

settings: RunContextSettings;

298

helpers: YeomanTest;

299

askedQuestions: AskedQuestions;

300

}

301

302

type Dependency = string | Parameters<DefaultEnvironmentApi['register']>;

303

304

type AskedQuestions = Array<{ name: string; answer: any }>;

305

306

interface TestAdapterOptions {

307

mockedAnswers?: PromptAnswers;

308

callback?: DummyPromptCallback;

309

}

310

311

type DummyPromptCallback = (prompt: any) => any;

312

313

type MockedGeneratorFactory<GenParameter extends BaseGenerator = DefaultGeneratorApi> = (

314

GeneratorClass?: GetGeneratorConstructor<GenParameter>

315

) => GetGeneratorConstructor<GenParameter>;

316

```