or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

binary-targets.mdindex.mdnode-api-support.mdplatform-detection.mdtest-utilities.md

test-utilities.mddocs/

0

# Test Utilities

1

2

Comprehensive testing utilities for platform-related functionality. The main package exports Jest utilities through the public API, while additional utilities for Vitest and binary target matching are available in the source but not officially exported through the main package entry point.

3

4

## Capabilities

5

6

### Jest Test Context

7

8

Complete test context system for Jest-based testing with temporary directories, filesystem utilities, and process mocking.

9

10

```typescript { .api }

11

/**

12

* Jest context factory for creating isolated test environments

13

*/

14

const jestContext: {

15

new(ctx?: BaseContext): ContextBuilder<BaseContext>;

16

};

17

18

/**

19

* Base test context interface providing core testing utilities

20

*/

21

interface BaseContext {

22

tmpDir: string;

23

fs: FSJetpack;

24

mocked: { cwd: string };

25

fixture: (name: string) => void;

26

cli: (...input: string[]) => ExecaChildProcess<string>;

27

printDir: (dir: string, extensions: string[]) => void;

28

tree: (itemPath?: string, indent?: string) => void;

29

}

30

```

31

32

**Usage Examples:**

33

34

```typescript

35

import { jestContext } from "@prisma/get-platform";

36

37

const ctx = jestContext.new().assemble();

38

39

beforeEach(() => {

40

// ctx.tmpDir is automatically created

41

// ctx.fs is bound to the temporary directory

42

// process.cwd() is changed to tmpDir

43

});

44

45

afterEach(() => {

46

// Original cwd is restored

47

// Temporary directory is cleaned up

48

});

49

50

test("platform detection in isolated environment", () => {

51

// Use ctx.fs for file operations in tmpDir

52

ctx.fs.write("test-file.txt", "content");

53

54

// Load a test fixture

55

ctx.fixture("platform-test-data");

56

57

// Print directory contents

58

const files = ctx.printDir(".", [".js", ".ts"]);

59

console.log(files);

60

});

61

```

62

63

### Jest Console Mocking

64

65

Console mocking utilities for capturing and testing console output in Jest.

66

67

```typescript { .api }

68

/**

69

* Console mocking context contributor for Jest

70

*/

71

const jestConsoleContext: <Ctx extends BaseContext>() => ContextContributor<Ctx, ConsoleContext>;

72

73

interface ConsoleContext {

74

mocked: {

75

'console.error': jest.SpyInstance;

76

'console.log': jest.SpyInstance;

77

'console.info': jest.SpyInstance;

78

'console.warn': jest.SpyInstance;

79

};

80

}

81

```

82

83

**Usage Examples:**

84

85

```typescript

86

import { jestContext, jestConsoleContext } from "@prisma/get-platform";

87

88

const ctx = jestContext.new()

89

.add(jestConsoleContext())

90

.assemble();

91

92

test("console output capture", () => {

93

console.warn("test warning");

94

95

expect(ctx.mocked['console.warn']).toHaveBeenCalledWith("test warning");

96

expect(ctx.mocked['console.error']).not.toHaveBeenCalled();

97

});

98

```

99

100

### Jest Process Mocking

101

102

Process stdout/stderr and exit mocking for Jest testing.

103

104

```typescript { .api }

105

/**

106

* Process output mocking context contributor for Jest

107

*/

108

const jestStdoutContext: <Ctx extends BaseContext>(

109

settings?: ProcessContextSettings

110

) => ContextContributor<Ctx, ProcessContext>;

111

112

/**

113

* Process exit mocking context contributor for Jest

114

*/

115

const processExitContext: <C extends BaseContext>() => ContextContributor<C, ProcessExitContext>;

116

117

interface ProcessContext {

118

mocked: {

119

'process.stderr.write': jest.SpyInstance;

120

'process.stdout.write': jest.SpyInstance;

121

};

122

normalizedCapturedStdout: () => string;

123

normalizedCapturedStderr: () => string;

124

clearCapturedStdout: () => void;

125

clearCapturedStderr: () => void;

126

}

127

128

interface ProcessExitContext {

129

mocked: { 'process.exit': jest.SpyInstance };

130

recordedExitCode: () => number;

131

}

132

133

interface ProcessContextSettings {

134

normalizationRules: [RegExp | string, string][];

135

}

136

```

137

138

**Usage Examples:**

139

140

```typescript

141

import { jestContext, jestStdoutContext, processExitContext } from "@prisma/get-platform";

142

143

const ctx = jestContext.new()

144

.add(jestStdoutContext({

145

normalizationRules: [

146

[/\/tmp\/[^/]+/g, '/tmp/normalized'],

147

[/\d{4}-\d{2}-\d{2}/g, 'YYYY-MM-DD']

148

]

149

}))

150

.add(processExitContext())

151

.assemble();

152

153

test("process output and exit", () => {

154

process.stdout.write("test output");

155

process.exit(42);

156

157

expect(ctx.normalizedCapturedStdout()).toBe("test output");

158

expect(ctx.recordedExitCode()).toBe(42);

159

});

160

```

161

162

### Vitest Test Context

163

164

**Note**: Vitest utilities are available in the source code but not exported through the main package entry point. They would need to be imported from individual source files if used.

165

166

Complete test context system for Vitest-based testing, mirroring Jest functionality.

167

168

```typescript { .api }

169

/**

170

* Vitest context factory for creating isolated test environments

171

*/

172

const vitestContext: {

173

new(ctx?: BaseContext): ContextBuilder<BaseContext>;

174

};

175

176

/**

177

* Console mocking context contributor for Vitest

178

*/

179

const vitestConsoleContext: <Ctx extends BaseContext>() => ContextContributor<Ctx, ConsoleContext>;

180

181

/**

182

* Process output mocking context contributor for Vitest

183

*/

184

const vitestStdoutContext: <Ctx extends BaseContext>(

185

settings?: ProcessContextSettings

186

) => ContextContributor<Ctx, ProcessContext>;

187

188

/**

189

* Process exit mocking context contributor for Vitest

190

*/

191

const vitestProcessExitContext: <C extends BaseContext>() => ContextContributor<C, ProcessExitContext>;

192

```

193

194

**Usage Examples:**

195

196

```typescript

197

import { vitestContext, vitestConsoleContext } from "@prisma/get-platform";

198

import { beforeEach, afterEach, test, expect } from "vitest";

199

200

const ctx = vitestContext.new()

201

.add(vitestConsoleContext())

202

.assemble();

203

204

test("vitest platform testing", () => {

205

// Same API as Jest context

206

ctx.fs.write("config.json", JSON.stringify({ platform: "test" }));

207

208

console.log("test message");

209

expect(ctx.mocked['console.log']).toHaveBeenCalledWith("test message");

210

});

211

```

212

213

### Binary Target Regex

214

215

**Note**: Binary target regex is available in the source code but not exported through the main package entry point.

216

217

Regular expression for matching binary target names in strings, useful for testing and string processing.

218

219

```typescript { .api }

220

/**

221

* Regular expression that matches all supported binary target names

222

* Platform names are sorted by length (descending) to ensure longest match

223

*/

224

const binaryTargetRegex: RegExp;

225

```

226

227

**Usage Examples:**

228

229

```typescript

230

import { binaryTargetRegex } from "@prisma/get-platform";

231

232

// Extract binary targets from strings

233

const logMessage = "Downloading engines for darwin-arm64 and linux-musl-openssl-3.0.x";

234

const matches = logMessage.match(binaryTargetRegex);

235

console.log(matches);

236

// ["darwin-arm64", "linux-musl-openssl-3.0.x"]

237

238

// Replace binary targets in text

239

const normalized = logMessage.replace(binaryTargetRegex, "[BINARY_TARGET]");

240

console.log(normalized);

241

// "Downloading engines for [BINARY_TARGET] and [BINARY_TARGET]"

242

243

// Validate if string contains valid binary targets

244

function containsValidTargets(text: string): boolean {

245

return binaryTargetRegex.test(text);

246

}

247

```

248

249

### Link Utility

250

251

Terminal-friendly link formatting utility for creating clickable links with fallback support.

252

253

```typescript { .api }

254

/**

255

* Creates terminal-friendly links with fallback to underlined text

256

* @param url - URL to create link for

257

* @returns Formatted link string

258

*/

259

function link(url: any): string;

260

```

261

262

**Usage Examples:**

263

264

```typescript

265

import { link } from "@prisma/get-platform";

266

267

// Create terminal link

268

const helpLink = link("https://prisma.io/docs");

269

console.log(helpLink);

270

// In terminals with link support: clickable link

271

// In terminals without link support: underlined URL

272

273

// Use in error messages

274

function showError(message: string) {

275

console.error(`${message}\nFor help, visit: ${link("https://github.com/prisma/prisma/issues")}`);

276

}

277

```

278

279

## Context Builder Pattern

280

281

The test utilities use a builder pattern for composing test contexts:

282

283

```typescript { .api }

284

interface ContextBuilder<Context> {

285

add<NewContext>(contributor: ContextContributor<Context, NewContext>): ContextBuilder<Context & NewContext>;

286

assemble(): Context;

287

}

288

289

type ContextContributor<Context, NewContext> = (ctx: Context) => Context & NewContext;

290

```

291

292

**Usage Examples:**

293

294

```typescript

295

// Build complex test context

296

const ctx = jestContext.new()

297

.add(jestConsoleContext())

298

.add(jestStdoutContext({

299

normalizationRules: [[/\d+/g, 'NUMBER']]

300

}))

301

.add(processExitContext())

302

.assemble();

303

304

// Now ctx has all capabilities:

305

// - Base context (tmpDir, fs, etc.)

306

// - Console mocking

307

// - Process output capture with normalization

308

// - Process exit capture

309

```

310

311

## Testing Best Practices

312

313

**Isolation**: Each test gets a fresh temporary directory and clean mocks

314

315

**Cleanup**: All mocks are automatically restored after each test

316

317

**Fixtures**: Use `ctx.fixture()` to load predefined test data

318

319

**Normalization**: Use normalization rules to make output predictable across environments

320

321

**Cross-framework**: Same API works for both Jest and Vitest with appropriate imports