0
# Test Discovery
1
2
Core functionality for finding and filtering test files based on patterns, changed files, and dependencies. The SearchSource class provides comprehensive test discovery capabilities essential for watch mode, selective test running, and IDE integration.
3
4
## Capabilities
5
6
### SearchSource Class
7
8
The main class for test discovery operations, handling file pattern matching and dependency resolution.
9
10
```typescript { .api }
11
/**
12
* Handles test discovery and filtering based on configuration patterns
13
*/
14
export default class SearchSource {
15
/**
16
* Creates a SearchSource instance with the given test context
17
* @param context - Test context containing configuration and file system access
18
*/
19
constructor(context: TestContext);
20
}
21
```
22
23
**Usage Example:**
24
25
```typescript
26
import { SearchSource } from "@jest/core";
27
import Runtime from "jest-runtime";
28
import { normalize } from "jest-config";
29
30
// Setup configuration and context
31
const { options: config } = await normalize({
32
rootDir: "./src",
33
testMatch: ["**/__tests__/**/*.test.js"],
34
}, {});
35
36
const context = await Runtime.createContext(config, {
37
maxWorkers: 1,
38
watchman: false,
39
});
40
41
// Create SearchSource instance
42
const searchSource = new SearchSource(context);
43
```
44
45
### Test File Path Validation
46
47
Determines whether a given file path matches the configured test patterns.
48
49
```typescript { .api }
50
/**
51
* Checks if a file path is considered a test file based on configuration
52
* @param path - File path to check
53
* @returns True if the path matches test patterns
54
*/
55
isTestFilePath(path: string): boolean;
56
```
57
58
**Usage Example:**
59
60
```typescript
61
const isTest = searchSource.isTestFilePath("/src/components/__tests__/Button.test.js");
62
// Returns: true
63
64
const isNotTest = searchSource.isTestFilePath("/src/components/Button.js");
65
// Returns: false
66
```
67
68
### Pattern-Based Test Discovery
69
70
Finds all tests matching specific path patterns.
71
72
```typescript { .api }
73
/**
74
* Finds tests matching the provided path patterns
75
* @param testPathPatternsExecutor - Pattern executor for filtering test paths
76
* @returns Search result containing matching tests and statistics
77
*/
78
findMatchingTests(testPathPatternsExecutor: TestPathPatternsExecutor): SearchResult;
79
```
80
81
**Usage Example:**
82
83
```typescript
84
import { TestPathPatterns } from "@jest/pattern";
85
86
const patterns = new TestPathPatterns(["Button"], "");
87
const executor = patterns.toExecutor();
88
89
const result = searchSource.findMatchingTests(executor);
90
console.log(`Found ${result.tests.length} tests`);
91
console.log("Statistics:", result.stats);
92
```
93
94
### Related Test Discovery
95
96
Finds tests related to specific source files, useful for watch mode and coverage collection.
97
98
```typescript { .api }
99
/**
100
* Finds tests related to a set of file paths using dependency analysis
101
* @param allPaths - Set of file paths to find related tests for
102
* @param collectCoverage - Whether to collect coverage information
103
* @returns Search result with related tests and optional coverage data
104
*/
105
async findRelatedTests(
106
allPaths: Set<string>,
107
collectCoverage: boolean
108
): Promise<SearchResult>;
109
```
110
111
**Usage Example:**
112
113
```typescript
114
// Find tests related to changed source files
115
const changedFiles = new Set([
116
"/src/components/Button.js",
117
"/src/utils/helpers.js"
118
]);
119
120
const result = await searchSource.findRelatedTests(changedFiles, true);
121
console.log(`Found ${result.tests.length} related tests`);
122
123
if (result.collectCoverageFrom) {
124
console.log("Coverage will be collected from:", result.collectCoverageFrom);
125
}
126
```
127
128
### Path-Based Test Discovery
129
130
Finds tests for specific file paths.
131
132
```typescript { .api }
133
/**
134
* Returns tests for specific file paths
135
* @param paths - Array of file paths to check for tests
136
* @returns Search result containing tests from the specified paths
137
*/
138
findTestsByPaths(paths: Array<string>): SearchResult;
139
```
140
141
**Usage Example:**
142
143
```typescript
144
const testPaths = [
145
"/src/components/__tests__/Button.test.js",
146
"/src/utils/__tests__/helpers.test.js"
147
];
148
149
const result = searchSource.findTestsByPaths(testPaths);
150
console.log(`Found ${result.tests.length} tests at specified paths`);
151
```
152
153
### Pattern-Based Related Test Discovery
154
155
Finds related tests from path patterns with coverage collection support.
156
157
```typescript { .api }
158
/**
159
* Finds related tests from path patterns
160
* @param paths - Array of file path patterns
161
* @param collectCoverage - Whether to collect coverage information
162
* @returns Search result with related tests
163
*/
164
async findRelatedTestsFromPattern(
165
paths: Array<string>,
166
collectCoverage: boolean
167
): Promise<SearchResult>;
168
```
169
170
### Changed File Test Discovery
171
172
Finds tests related to changed files, optimized for version control integration.
173
174
```typescript { .api }
175
/**
176
* Finds tests related to changed files from VCS information
177
* @param changedFilesInfo - Information about changed files from VCS
178
* @param collectCoverage - Whether to collect coverage information
179
* @returns Search result with tests related to changed files
180
*/
181
async findTestRelatedToChangedFiles(
182
changedFilesInfo: ChangedFiles,
183
collectCoverage: boolean
184
): Promise<SearchResult>;
185
```
186
187
### Advanced Test Path Discovery
188
189
Gets test paths based on global and project configuration, supporting various Jest CLI options.
190
191
```typescript { .api }
192
/**
193
* Gets test paths based on configuration and optional changed files
194
* @param globalConfig - Jest global configuration
195
* @param projectConfig - Project-specific configuration
196
* @param changedFiles - Optional changed files information
197
* @param filter - Optional filter function for test paths
198
* @returns Search result based on configuration
199
*/
200
async getTestPaths(
201
globalConfig: Config.GlobalConfig,
202
projectConfig: Config.ProjectConfig,
203
changedFiles?: ChangedFiles,
204
filter?: Filter
205
): Promise<SearchResult>;
206
```
207
208
### Source File Discovery
209
210
Finds source files related to changed test files.
211
212
```typescript { .api }
213
/**
214
* Finds source files related to changed test files
215
* @param changedFilesInfo - Information about changed files
216
* @returns Array of related source file paths
217
*/
218
async findRelatedSourcesFromTestsInChangedFiles(
219
changedFilesInfo: ChangedFiles
220
): Promise<Array<string>>;
221
```
222
223
### Windows Path Filtering
224
225
Filters and resolves paths on Windows platform using case-insensitive matching.
226
227
```typescript { .api }
228
/**
229
* Filters and resolves paths on Windows platform using case-insensitive matching
230
* @param paths - Array of file paths to filter and resolve
231
* @returns Array of resolved and filtered paths
232
*/
233
filterPathsWin32(paths: Array<string>): Array<string>;
234
```
235
236
## Types
237
238
```typescript { .api }
239
interface SearchResult {
240
/** Indicates if no source control management was found */
241
noSCM?: boolean;
242
/** Statistics about test path matching */
243
stats?: Stats;
244
/** Set of files to collect coverage from */
245
collectCoverageFrom?: Set<string>;
246
/** Array of discovered test files */
247
tests: Array<Test>;
248
/** Total number of tests found */
249
total?: number;
250
}
251
252
interface Stats {
253
/** Tests matching root directories */
254
roots: number;
255
/** Tests matching testMatch patterns */
256
testMatch: number;
257
/** Tests matching ignore patterns */
258
testPathIgnorePatterns: number;
259
/** Tests matching regex patterns */
260
testRegex: number;
261
/** Tests matching path patterns */
262
testPathPatterns?: number;
263
}
264
265
interface ChangedFiles {
266
/** Set of changed file paths */
267
changedFiles: Set<string>;
268
/** Repository information */
269
repos: {
270
git: Set<string>;
271
hg: Set<string>;
272
sl: Set<string>;
273
};
274
}
275
```