0
# Jest Pattern
1
2
Jest Pattern is a helper library for the Jest testing framework that implements pattern parsing and matching logic for test path filtering. It provides cross-platform pattern matching capabilities that handle both absolute and relative file paths, with sophisticated regex-based matching and Windows/POSIX path separator normalization.
3
4
## Package Information
5
6
- **Package Name**: @jest/pattern
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @jest/pattern`
10
11
## Core Imports
12
13
```typescript
14
import { TestPathPatterns, TestPathPatternsExecutor, type TestPathPatternsExecutorOptions } from "@jest/pattern";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { TestPathPatterns, TestPathPatternsExecutor } = require("@jest/pattern");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { TestPathPatterns } from "@jest/pattern";
27
28
// Create pattern collection
29
const patterns = new TestPathPatterns(["**/*.test.js", "./src/**/*"]);
30
31
// Validate patterns
32
if (patterns.isValid()) {
33
// Create executor with root directory
34
const executor = patterns.toExecutor({ rootDir: "/project" });
35
36
// Test file paths against patterns
37
const matches = executor.isMatch("/project/src/utils.test.js"); // true
38
const noMatch = executor.isMatch("/project/docs/readme.md"); // false
39
}
40
```
41
42
## Architecture
43
44
Jest Pattern is built around two primary components:
45
46
- **TestPathPatterns**: Manages collections of pattern strings and provides validation/conversion methods
47
- **TestPathPatternsExecutor**: Handles pattern execution with cross-platform path matching logic
48
- **Pattern Processing**: Converts string patterns to case-insensitive regular expressions with path separator normalization
49
- **Cross-Platform Support**: Handles both Windows backslash and POSIX forward slash path separators automatically
50
51
## Capabilities
52
53
### Pattern Collection Management
54
55
Manages collections of test path patterns with validation and conversion capabilities.
56
57
```typescript { .api }
58
/**
59
* Manages collections of test path patterns for Jest test discovery
60
*/
61
class TestPathPatterns {
62
/** Array of pattern strings provided during construction */
63
readonly patterns: Array<string>;
64
65
/**
66
* Creates a new TestPathPatterns instance
67
* @param patterns - Array of pattern strings to manage
68
*/
69
constructor(patterns: Array<string>);
70
71
/**
72
* Check if any patterns are configured
73
* @returns true if patterns array is not empty
74
*/
75
isSet(): boolean;
76
77
/**
78
* Validate that all patterns form valid regular expressions
79
* @returns true if all patterns compile to valid regex
80
*/
81
isValid(): boolean;
82
83
/**
84
* Get human-readable representation of patterns
85
* @returns patterns joined with '|' separator
86
*/
87
toPretty(): string;
88
89
/**
90
* Create executor for pattern matching operations
91
* @param options - Configuration options including rootDir
92
* @returns TestPathPatternsExecutor instance
93
*/
94
toExecutor(options: TestPathPatternsExecutorOptions): TestPathPatternsExecutor;
95
96
/**
97
* Serialize patterns for Jest serializers
98
* @returns serialization object with patterns and type
99
*/
100
toJSON(): any;
101
}
102
```
103
104
### Pattern Execution
105
106
Executes pattern matching operations against file paths with cross-platform support.
107
108
```typescript { .api }
109
/**
110
* Executes pattern matching operations with cross-platform path handling
111
*/
112
class TestPathPatternsExecutor {
113
/** Reference to the pattern collection */
114
readonly patterns: TestPathPatterns;
115
116
/**
117
* Creates a new TestPathPatternsExecutor
118
* @param patterns - TestPathPatterns instance to execute
119
* @param options - Configuration options for execution
120
*/
121
constructor(patterns: TestPathPatterns, options: TestPathPatternsExecutorOptions);
122
123
/**
124
* Check if any patterns are configured
125
* @returns true if patterns are set (delegates to patterns.isSet())
126
*/
127
isSet(): boolean;
128
129
/**
130
* Validate that all patterns form valid regular expressions
131
* @returns true if all patterns compile successfully
132
*/
133
isValid(): boolean;
134
135
/**
136
* Test if absolute path matches any configured pattern
137
* @param absPath - Absolute file path to test against patterns
138
* @returns true if path matches any pattern
139
* @throws Error if patterns form invalid regex
140
*/
141
isMatch(absPath: string): boolean;
142
143
/**
144
* Get human-readable representation of patterns
145
* @returns patterns joined with '|' separator (delegates to patterns.toPretty())
146
*/
147
toPretty(): string;
148
}
149
```
150
151
### Configuration Options
152
153
Configuration interface for TestPathPatternsExecutor behavior.
154
155
```typescript { .api }
156
/**
157
* Configuration options for TestPathPatternsExecutor
158
*/
159
interface TestPathPatternsExecutorOptions {
160
/** Root directory for resolving relative patterns */
161
rootDir: string;
162
}
163
```
164
165
## Pattern Matching Behavior
166
167
### Pattern Types
168
- **Relative patterns**: `./src/**/*.test.js` - matched against relative path from rootDir
169
- **Absolute patterns**: `/project/tests/**/*` - matched against absolute path
170
- **Mixed patterns**: Supports both types in the same pattern collection
171
172
### Cross-Platform Support
173
- **Windows paths**: Automatically handles backslash separators (`\`)
174
- **POSIX paths**: Handles forward slash separators (`/`)
175
- **Pattern normalization**: Converts path separators in patterns to work with target platform
176
177
### Special Pattern Handling
178
- **Dot prefix patterns**: `./foo.test.js` converts to `^foo.test.js` regex
179
- **Windows dot prefix**: `.\foo.test.js` converts to `^foo.test.js` regex
180
- **Case-insensitive matching**: All pattern matching is case-insensitive
181
- **Empty patterns**: Empty pattern array matches all paths (returns true)
182
183
### Path Resolution
184
- **Dual testing**: Tests patterns against both absolute and relative path versions
185
- **Relative path calculation**: Uses `path.relative(rootDir, absPath)` for relative pattern matching
186
- **Pattern compilation**: Converts string patterns to RegExp with case-insensitive flag
187
188
## Error Handling
189
190
- **Invalid regex patterns**: `isValid()` returns false for patterns that don't compile to valid regex
191
- **Runtime regex errors**: `isMatch()` throws errors if patterns form invalid regex during execution
192
- **Path resolution**: Uses Node.js `path` module for reliable cross-platform path operations
193
194
## Usage Examples
195
196
### Basic Pattern Matching
197
198
```typescript
199
import { TestPathPatterns } from "@jest/pattern";
200
201
const patterns = new TestPathPatterns(["**/*.test.js", "!**/node_modules/**"]);
202
const executor = patterns.toExecutor({ rootDir: "/my-project" });
203
204
// Test various paths
205
console.log(executor.isMatch("/my-project/src/utils.test.js")); // true
206
console.log(executor.isMatch("/my-project/src/utils.js")); // false
207
console.log(executor.isMatch("/my-project/node_modules/lib/test.js")); // false
208
```
209
210
### Validation and Error Handling
211
212
```typescript
213
import { TestPathPatterns } from "@jest/pattern";
214
215
const patterns = new TestPathPatterns(["[invalid-regex"]);
216
217
if (!patterns.isValid()) {
218
console.log("Invalid patterns detected");
219
// Handle invalid patterns appropriately
220
} else {
221
const executor = patterns.toExecutor({ rootDir: "/project" });
222
// Safe to use executor
223
}
224
```
225
226
### Pretty Printing for Debugging
227
228
```typescript
229
import { TestPathPatterns } from "@jest/pattern";
230
231
const patterns = new TestPathPatterns(["src/**/*.test.js", "tests/**/*"]);
232
console.log("Patterns:", patterns.toPretty()); // "src/**/*.test.js|tests/**/*"
233
234
const executor = patterns.toExecutor({ rootDir: "/project" });
235
console.log("Executor patterns:", executor.toPretty()); // Same output
236
```