0
# Terminal Interaction
1
2
Terminal and TTY interaction utilities for Jest's interactive features and output control. These utilities manage terminal state detection, output clearing, and special character handling across different platforms and environments.
3
4
## Capabilities
5
6
### Clear Line
7
8
Clears the current line in a TTY stream using ANSI escape codes, commonly used for updating progress indicators and dynamic output.
9
10
```typescript { .api }
11
/**
12
* Clears the current line in a TTY stream
13
* @param stream - The TTY write stream to clear
14
*/
15
function clearLine(stream: WriteStream): void;
16
```
17
18
**Usage Examples:**
19
20
```typescript
21
import { clearLine } from "jest-util";
22
23
// Clear current line in stdout
24
clearLine(process.stdout);
25
26
// Clear current line in stderr
27
clearLine(process.stderr);
28
29
// Progress indicator with line clearing
30
function showProgress(current: number, total: number) {
31
clearLine(process.stdout);
32
process.stdout.write(`Progress: ${current}/${total} (${Math.round(current/total * 100)}%)`);
33
}
34
35
// Jest test runner progress
36
function updateTestProgress(completed: number, total: number) {
37
if (process.stdout.isTTY) {
38
clearLine(process.stdout);
39
process.stdout.write(`Tests: ${completed}/${total} completed`);
40
}
41
}
42
43
// Dynamic status updates
44
let dots = 0;
45
const statusInterval = setInterval(() => {
46
if (process.stdout.isTTY) {
47
clearLine(process.stdout);
48
process.stdout.write(`Running tests${'.'.repeat(dots % 4)}`);
49
dots++;
50
}
51
}, 500);
52
```
53
54
**Behavior:**
55
- Only operates on TTY streams - no-op for non-TTY streams
56
- Sends ANSI escape sequence `\r\x1b[K` to clear line
57
- Positions cursor at beginning of line after clearing
58
59
### Is Interactive
60
61
Boolean constant indicating whether the current environment supports interactive terminal features.
62
63
```typescript { .api }
64
/**
65
* Boolean indicating if environment supports interactive features
66
*/
67
const isInteractive: boolean;
68
```
69
70
**Usage Examples:**
71
72
```typescript
73
import { isInteractive } from "jest-util";
74
75
// Conditional interactive features
76
if (isInteractive) {
77
console.log("Running in interactive mode");
78
// Show progress bars, colored output, etc.
79
} else {
80
console.log("Running in non-interactive mode");
81
// Plain text output for CI/CD
82
}
83
84
// Jest watch mode detection
85
function shouldEnableWatchMode(): boolean {
86
return isInteractive && !process.env.CI;
87
}
88
89
// Progress reporting
90
function reportProgress(current: number, total: number) {
91
if (isInteractive) {
92
// Show dynamic progress bar
93
clearLine(process.stdout);
94
process.stdout.write(`[${'='.repeat(current)}${' '.repeat(total-current)}] ${current}/${total}`);
95
} else {
96
// Log discrete progress updates
97
if (current % 10 === 0) {
98
console.log(`Progress: ${current}/${total}`);
99
}
100
}
101
}
102
```
103
104
**Detection Logic:**
105
- Returns `false` if running in CI environment (detected via `ci-info`)
106
- Returns `false` if `process.stdout` is null
107
- Returns `false` if `TERM` environment variable is 'dumb'
108
- Returns `true` if `process.stdout.isTTY` is true
109
- Otherwise returns `false`
110
111
### Special Characters
112
113
Collection of Unicode characters and ANSI sequences for consistent terminal output across platforms.
114
115
```typescript { .api }
116
/**
117
* Collection of special characters for terminal output
118
*/
119
const specialChars: {
120
/** Arrow character for indicating direction or selection */
121
ARROW: string;
122
/** Status icons for test results */
123
ICONS: {
124
/** Cross mark for failed tests */
125
failed: string;
126
/** Circle for pending tests */
127
pending: string;
128
/** Check mark for successful tests */
129
success: string;
130
/** Pencil for todo items */
131
todo: string;
132
};
133
/** ANSI clear screen sequence */
134
CLEAR: string;
135
};
136
```
137
138
**Usage Examples:**
139
140
```typescript
141
import { specialChars } from "jest-util";
142
143
// Test result formatting
144
function formatTestResult(status: 'passed' | 'failed' | 'pending' | 'todo', name: string) {
145
let icon: string;
146
switch (status) {
147
case 'passed': icon = specialChars.ICONS.success; break;
148
case 'failed': icon = specialChars.ICONS.failed; break;
149
case 'pending': icon = specialChars.ICONS.pending; break;
150
case 'todo': icon = specialChars.ICONS.todo; break;
151
}
152
153
return `${icon} ${name}`;
154
}
155
156
// Examples:
157
// formatTestResult('passed', 'should add numbers') → "✓ should add numbers"
158
// formatTestResult('failed', 'should handle errors') → "✗ should handle errors"
159
160
// Navigation indicators
161
function showSelected(items: string[], selectedIndex: number) {
162
items.forEach((item, index) => {
163
const prefix = index === selectedIndex ? specialChars.ARROW : ' ';
164
console.log(`${prefix} ${item}`);
165
});
166
}
167
168
// Clear screen for fresh output
169
function clearScreen() {
170
process.stdout.write(specialChars.CLEAR);
171
}
172
173
// Test suite header
174
function printTestSuiteHeader() {
175
clearScreen();
176
console.log(`${specialChars.ICONS.success} Jest Test Suite`);
177
console.log(`${specialChars.ARROW} Running tests...`);
178
}
179
```
180
181
**Character Values:**
182
- `ARROW`: ` › ` (bullet point with spaces)
183
- `ICONS.failed`: Platform-specific cross mark (✗ or ×)
184
- `ICONS.pending`: `○` (hollow circle)
185
- `ICONS.success`: Platform-specific check mark (✓ or √)
186
- `ICONS.todo`: `✎` (pencil)
187
- `CLEAR`: Platform-specific ANSI clear sequence
188
189
### Pre-Run Message
190
191
Utilities for displaying and managing the "Determining test suites to run..." message during Jest's initialization phase.
192
193
```typescript { .api }
194
/**
195
* Pre-run message utilities for Jest initialization
196
*/
197
const preRunMessage: {
198
/** Display the pre-run message in interactive mode */
199
print(stream: WriteStream): void;
200
/** Clear the pre-run message in interactive mode */
201
remove(stream: WriteStream): void;
202
};
203
```
204
205
**Usage Examples:**
206
207
```typescript
208
import { preRunMessage } from "jest-util";
209
210
// Jest initialization sequence
211
function initializeTestRun() {
212
// Show loading message
213
preRunMessage.print(process.stdout);
214
215
// Perform test discovery and setup
216
await discoverTestFiles();
217
await setupTestEnvironment();
218
219
// Clear loading message before starting tests
220
preRunMessage.remove(process.stdout);
221
222
console.log("Starting test execution...");
223
}
224
225
// Custom loading sequence
226
function showInitializationProgress() {
227
preRunMessage.print(process.stdout);
228
229
setTimeout(() => {
230
preRunMessage.remove(process.stdout);
231
console.log("Initialization complete!");
232
}, 2000);
233
}
234
235
// Conditional message display
236
function conditionalPreRunMessage() {
237
if (process.env.VERBOSE !== 'true') {
238
preRunMessage.print(process.stdout);
239
240
// Later, after setup is complete
241
preRunMessage.remove(process.stdout);
242
}
243
}
244
```
245
246
**Behavior:**
247
- **Interactive Mode Only**: Messages are only displayed when `isInteractive` is true
248
- **Non-TTY Safe**: No output occurs on non-TTY streams
249
- **Message Content**: Displays "Determining test suites to run..." with appropriate styling
250
- **Clean Removal**: `remove()` clears the message line completely
251
252
## Types
253
254
```typescript { .api }
255
// Node.js WriteStream interface
256
interface WriteStream {
257
write(chunk: any): boolean;
258
isTTY?: boolean;
259
}
260
```
261
262
**Platform Compatibility:**
263
- **Windows**: Uses appropriate Unicode characters and ANSI sequences
264
- **Unix/Linux**: Uses standard terminal control sequences
265
- **CI Environments**: Automatically detects and disables interactive features
266
- **SSH Sessions**: Respects TTY detection for remote terminal sessions