@terreno/test 57.18.0 → 57.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2074 -0
- package/README.md +6 -0
- package/dist/assertions/expectAPIError.d.ts +18 -0
- package/dist/assertions/expectAPIError.js +33 -0
- package/dist/assertions/strictResponseProperties.d.ts +14 -0
- package/dist/assertions/strictResponseProperties.js +37 -0
- package/dist/cache/mongoTestCache.js +2 -2
- package/dist/cli/collectFiles.d.ts +38 -0
- package/dist/cli/collectFiles.js +73 -0
- package/dist/cli/testHygiene.d.ts +134 -0
- package/dist/cli/testHygiene.js +357 -0
- package/dist/cli/testHygieneCli.d.ts +2 -0
- package/dist/cli/testHygieneCli.js +5 -0
- package/dist/cli/testHygieneRules.d.ts +58 -0
- package/dist/cli/testHygieneRules.js +517 -0
- package/dist/cli/testShard.d.ts +155 -0
- package/dist/cli/testShard.js +377 -0
- package/dist/cli/testShardCli.d.ts +2 -0
- package/dist/cli/testShardCli.js +5 -0
- package/dist/expo/authTokenStorage.d.ts +76 -0
- package/dist/expo/authTokenStorage.js +160 -0
- package/dist/expo/expoModuleMocks.d.ts +24 -0
- package/dist/expo/expoModuleMocks.js +456 -0
- package/dist/expo/libraryModuleMocks.d.ts +17 -0
- package/dist/expo/libraryModuleMocks.js +347 -0
- package/dist/expo/mockHelpers.d.ts +39 -0
- package/dist/expo/mockHelpers.js +45 -0
- package/dist/expo/mockModuleAliases.d.ts +50 -0
- package/dist/expo/mockModuleAliases.js +174 -0
- package/dist/expo/reactNativeMock.d.ts +39 -0
- package/dist/expo/reactNativeMock.js +421 -0
- package/dist/expo/registerExpoTestEnvironment.d.ts +69 -0
- package/dist/expo/registerExpoTestEnvironment.js +165 -0
- package/dist/expo/renderWithTerreno.d.ts +47 -0
- package/dist/expo/renderWithTerreno.js +47 -0
- package/dist/http/authWithToken.d.ts +20 -0
- package/dist/http/authWithToken.js +30 -0
- package/dist/index.d.ts +14 -1
- package/dist/index.js +33 -1
- package/dist/logging/silenceLogs.js +0 -2
- package/dist/mocks/aiSdk.d.ts +77 -0
- package/dist/mocks/aiSdk.js +102 -0
- package/dist/mocks/cloudTasks.d.ts +91 -0
- package/dist/mocks/cloudTasks.js +197 -0
- package/dist/mocks/expoPush.d.ts +53 -0
- package/dist/mocks/expoPush.js +57 -0
- package/dist/mocks/gcs.d.ts +101 -0
- package/dist/mocks/gcs.js +162 -0
- package/dist/mocks/googleAuth.d.ts +69 -0
- package/dist/mocks/googleAuth.js +55 -0
- package/dist/mocks/mockGroup.d.ts +11 -0
- package/dist/mocks/mockGroup.js +21 -0
- package/dist/mocks/notifiers.d.ts +21 -0
- package/dist/mocks/notifiers.js +26 -0
- package/dist/mocks/sendgrid.d.ts +22 -0
- package/dist/mocks/sendgrid.js +32 -0
- package/dist/mocks/twilio.d.ts +72 -0
- package/dist/mocks/twilio.js +64 -0
- package/dist/preload/registerBackendPreload.js +4 -1
- package/dist/time/freezeTime.d.ts +16 -0
- package/dist/time/freezeTime.js +49 -0
- package/dist/transaction/testTransaction.d.ts +43 -6
- package/dist/transaction/testTransaction.js +371 -92
- package/dist/utils/waitUntil.d.ts +22 -0
- package/dist/utils/waitUntil.js +34 -0
- package/package.json +53 -8
- package/src/assertions/expectAPIError.ts +51 -0
- package/src/assertions/strictResponseProperties.ts +42 -0
- package/src/cache/mongoTestCache.ts +2 -2
- package/src/cli/collectFiles.ts +115 -0
- package/src/cli/testHygiene.ts +539 -0
- package/src/cli/testHygieneCli.ts +4 -0
- package/src/cli/testHygieneRules.ts +719 -0
- package/src/cli/testShard.ts +532 -0
- package/src/cli/testShardCli.ts +4 -0
- package/src/expo/authTokenStorage.ts +198 -0
- package/src/expo/expoModuleMocks.ts +503 -0
- package/src/expo/libraryModuleMocks.ts +411 -0
- package/src/expo/mockHelpers.ts +73 -0
- package/src/expo/mockModuleAliases.ts +252 -0
- package/src/expo/reactNativeMock.ts +534 -0
- package/src/expo/registerExpoTestEnvironment.ts +262 -0
- package/src/expo/renderWithTerreno.ts +79 -0
- package/src/http/authWithToken.ts +38 -0
- package/src/index.ts +82 -1
- package/src/logging/silenceLogs.ts +0 -2
- package/src/mocks/aiSdk.ts +199 -0
- package/src/mocks/cloudTasks.ts +323 -0
- package/src/mocks/expoPush.ts +134 -0
- package/src/mocks/gcs.ts +305 -0
- package/src/mocks/googleAuth.ts +136 -0
- package/src/mocks/mockGroup.ts +32 -0
- package/src/mocks/notifiers.ts +36 -0
- package/src/mocks/sendgrid.ts +57 -0
- package/src/mocks/twilio.ts +143 -0
- package/src/preload/registerBackendPreload.ts +4 -1
- package/src/time/freezeTime.ts +61 -0
- package/src/transaction/testTransaction.ts +456 -124
- package/src/utils/waitUntil.ts +47 -0
- package/biome.jsonc +0 -20
- package/bunfig.toml +0 -16
- package/src/cache/mongoTestCache.test.ts +0 -103
- package/src/env/setTerrenoTestEnv.test.ts +0 -26
- package/src/http/authAsUser.test.ts +0 -40
- package/src/http/getBaseServer.test.ts +0 -45
- package/src/logging/setupEnvironment.test.ts +0 -24
- package/src/logging/silenceLogs.test.ts +0 -52
- package/src/logging/testLogger.test.ts +0 -58
- package/src/mocks/sentryBun.test.ts +0 -230
- package/src/mongo/connection.test.ts +0 -43
- package/src/mongo/mongoServer.test.ts +0 -99
- package/src/preload/registerBackendPreload.test.ts +0 -10
- package/src/transaction/testTransaction.test.ts +0 -64
- package/src/utils/helpers.test.ts +0 -46
- package/tsconfig.json +0 -18
|
@@ -0,0 +1,719 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AST rules for the test-hygiene checker. Each rule targets a Bun test pattern that causes
|
|
3
|
+
* order-dependent or timing-dependent failures:
|
|
4
|
+
*
|
|
5
|
+
* - `no-module-scope-mock-module`: `mock.module()` is process-wide and has no undo, so a call
|
|
6
|
+
* that runs at module load leaks into every later file in the process. Register mocks from a
|
|
7
|
+
* helper called in `beforeEach`/`beforeAll`/`describe` instead.
|
|
8
|
+
* - `no-direct-barrel-mock`: mocking a shared barrel by one specifier (an alias like `@hooks`)
|
|
9
|
+
* leaves the other cache key (`hooks/index.ts`) bound to the real module. Route barrel mocks
|
|
10
|
+
* through helpers that register both keys.
|
|
11
|
+
* - `no-sleep`: fixed sleeps are either too short on slow CI or waste time locally. Poll the
|
|
12
|
+
* real condition instead.
|
|
13
|
+
* - `no-cache-busted-import`: `import("./x?bust")` creates a new module identity, so
|
|
14
|
+
* `mock.module()` registrations for `./x` no longer apply.
|
|
15
|
+
* - `no-late-real-capture`: capturing the real barrel inside the mock factory can re-enter the
|
|
16
|
+
* in-progress registration and bind a partial module. Capture real exports at module scope.
|
|
17
|
+
* - `no-component-snapshot`: `expect(ImportedComponent).toMatchSnapshot()` snapshots a function
|
|
18
|
+
* reference, not rendered output.
|
|
19
|
+
*
|
|
20
|
+
* Uses the TypeScript compiler API (not regex) so scope detection is reliable.
|
|
21
|
+
*/
|
|
22
|
+
import path from "node:path";
|
|
23
|
+
import ts from "typescript";
|
|
24
|
+
|
|
25
|
+
import {matchesAnyGlob, toPosixPath} from "./collectFiles";
|
|
26
|
+
|
|
27
|
+
export const HYGIENE_RULE_IDS = [
|
|
28
|
+
"no-module-scope-mock-module",
|
|
29
|
+
"no-direct-barrel-mock",
|
|
30
|
+
"no-sleep",
|
|
31
|
+
"no-cache-busted-import",
|
|
32
|
+
"no-late-real-capture",
|
|
33
|
+
"no-component-snapshot",
|
|
34
|
+
] as const;
|
|
35
|
+
|
|
36
|
+
export type HygieneRuleId = (typeof HYGIENE_RULE_IDS)[number];
|
|
37
|
+
|
|
38
|
+
export interface HygieneViolation {
|
|
39
|
+
/** Path relative to the configured root, POSIX separators. */
|
|
40
|
+
file: string;
|
|
41
|
+
/** 1-based line. */
|
|
42
|
+
line: number;
|
|
43
|
+
ruleId: HygieneRuleId;
|
|
44
|
+
message: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** App-specific knowledge the rules need. Every field is optional; empty disables that aspect. */
|
|
48
|
+
export interface HygieneRuleConfig {
|
|
49
|
+
/** Absolute directory that relative barrel paths and reported file paths are relative to. */
|
|
50
|
+
rootDir: string;
|
|
51
|
+
/**
|
|
52
|
+
* Globs matched against bare (non-relative) import specifiers that name a shared barrel,
|
|
53
|
+
* e.g. `@hooks`, `@store`, `@app/*`.
|
|
54
|
+
*/
|
|
55
|
+
barrelAliases?: readonly string[];
|
|
56
|
+
/**
|
|
57
|
+
* Globs matched against the root-relative, extension-stripped path a relative specifier
|
|
58
|
+
* resolves to, e.g. `hooks`, `store/sdk`. A trailing `/index` is also matched as its directory.
|
|
59
|
+
*/
|
|
60
|
+
barrelPaths?: readonly string[];
|
|
61
|
+
/** Globs of root-relative test files allowed to mock barrels directly (e.g. `tests/mocks/**`). */
|
|
62
|
+
barrelMockAllowlist?: readonly string[];
|
|
63
|
+
/**
|
|
64
|
+
* Module names or path suffixes (e.g. `bunModuleAliases`) whose named imports are helpers that
|
|
65
|
+
* register `mock.module()` internally and take the mock factory as their first argument.
|
|
66
|
+
*/
|
|
67
|
+
mockHelperModules?: readonly string[];
|
|
68
|
+
/** Module names or path suffixes exporting "get the real exports" helpers. */
|
|
69
|
+
realExportGetterModules?: readonly string[];
|
|
70
|
+
/** Regex source that a getter import's name must match (default: any name). */
|
|
71
|
+
realExportGetterNamePattern?: string;
|
|
72
|
+
/** Extra sleep callees flagged by `no-sleep`, as written at the call site (e.g. `Bun.sleep`). */
|
|
73
|
+
sleepCallees?: readonly string[];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export const DEFAULT_SLEEP_CALLEES: readonly string[] = ["Bun.sleep"];
|
|
77
|
+
|
|
78
|
+
const stripExtension = (filePath: string): string =>
|
|
79
|
+
filePath.replace(/\.(tsx?|jsx?|mjs|cjs)$/u, "");
|
|
80
|
+
|
|
81
|
+
/** Whether `specifier` is `entry` exactly or ends with `/entry` (ignoring a file extension). */
|
|
82
|
+
const specifierMatchesModule = ({
|
|
83
|
+
specifier,
|
|
84
|
+
modules,
|
|
85
|
+
}: {
|
|
86
|
+
specifier: string;
|
|
87
|
+
modules: readonly string[];
|
|
88
|
+
}): boolean => {
|
|
89
|
+
const stripped = stripExtension(specifier);
|
|
90
|
+
return modules.some((entry) => stripped === entry || stripped.endsWith(`/${entry}`));
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/** Determines whether a `mock.module()`/`require()`/`import()` specifier targets a shared barrel. */
|
|
94
|
+
export const resolvesToBarrel = ({
|
|
95
|
+
config,
|
|
96
|
+
fromFile,
|
|
97
|
+
specifier,
|
|
98
|
+
}: {
|
|
99
|
+
config: HygieneRuleConfig;
|
|
100
|
+
fromFile: string;
|
|
101
|
+
specifier: string;
|
|
102
|
+
}): boolean => {
|
|
103
|
+
if (!specifier.startsWith(".")) {
|
|
104
|
+
return matchesAnyGlob({filePath: specifier, globs: config.barrelAliases ?? []});
|
|
105
|
+
}
|
|
106
|
+
const barrelPaths = config.barrelPaths ?? [];
|
|
107
|
+
if (barrelPaths.length === 0) {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
const resolved = stripExtension(path.resolve(path.dirname(fromFile), specifier));
|
|
111
|
+
const relativeToRoot = toPosixPath(path.relative(config.rootDir, resolved));
|
|
112
|
+
const candidates = [relativeToRoot];
|
|
113
|
+
if (relativeToRoot.endsWith("/index")) {
|
|
114
|
+
candidates.push(relativeToRoot.slice(0, -"/index".length));
|
|
115
|
+
}
|
|
116
|
+
return candidates.some((candidate) => matchesAnyGlob({filePath: candidate, globs: barrelPaths}));
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const isMockModuleCallee = (expression: ts.Expression): boolean =>
|
|
120
|
+
ts.isPropertyAccessExpression(expression) &&
|
|
121
|
+
ts.isIdentifier(expression.expression) &&
|
|
122
|
+
expression.expression.text === "mock" &&
|
|
123
|
+
expression.name.text === "module";
|
|
124
|
+
|
|
125
|
+
const isMockModuleCall = (node: ts.Node): node is ts.CallExpression =>
|
|
126
|
+
ts.isCallExpression(node) && isMockModuleCallee(node.expression);
|
|
127
|
+
|
|
128
|
+
const isFunctionLike = (node: ts.Node): node is ts.FunctionLikeDeclaration =>
|
|
129
|
+
ts.isFunctionDeclaration(node) ||
|
|
130
|
+
ts.isFunctionExpression(node) ||
|
|
131
|
+
ts.isArrowFunction(node) ||
|
|
132
|
+
ts.isMethodDeclaration(node) ||
|
|
133
|
+
ts.isConstructorDeclaration(node) ||
|
|
134
|
+
ts.isGetAccessorDeclaration(node) ||
|
|
135
|
+
ts.isSetAccessorDeclaration(node);
|
|
136
|
+
|
|
137
|
+
/** Whether `node` runs at module load (no enclosing function). */
|
|
138
|
+
const isAtModuleScope = (node: ts.Node): boolean => {
|
|
139
|
+
let current: ts.Node | undefined = node.parent;
|
|
140
|
+
while (current) {
|
|
141
|
+
if (isFunctionLike(current)) {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
current = current.parent;
|
|
145
|
+
}
|
|
146
|
+
return true;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const makeViolation = ({
|
|
150
|
+
sourceFile,
|
|
151
|
+
node,
|
|
152
|
+
ruleId,
|
|
153
|
+
message,
|
|
154
|
+
}: {
|
|
155
|
+
sourceFile: ts.SourceFile;
|
|
156
|
+
node: ts.Node;
|
|
157
|
+
ruleId: HygieneRuleId;
|
|
158
|
+
message: string;
|
|
159
|
+
}): HygieneViolation => {
|
|
160
|
+
const {line} = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
|
|
161
|
+
return {file: sourceFile.fileName, line: line + 1, message, ruleId};
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
/** Calls `visitor` for every node in `root`, depth first. */
|
|
165
|
+
const walk = (root: ts.Node, visitor: (node: ts.Node) => void): void => {
|
|
166
|
+
const visit = (node: ts.Node): void => {
|
|
167
|
+
visitor(node);
|
|
168
|
+
ts.forEachChild(node, visit);
|
|
169
|
+
};
|
|
170
|
+
visit(root);
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/** Collects named functions (`function foo() {}` and `const foo = () => {}`) in the file. */
|
|
174
|
+
const collectNamedFunctions = (
|
|
175
|
+
sourceFile: ts.SourceFile
|
|
176
|
+
): Map<string, ts.FunctionLikeDeclaration> => {
|
|
177
|
+
const namedFunctions = new Map<string, ts.FunctionLikeDeclaration>();
|
|
178
|
+
walk(sourceFile, (node) => {
|
|
179
|
+
if (ts.isFunctionDeclaration(node) && node.name) {
|
|
180
|
+
namedFunctions.set(node.name.text, node);
|
|
181
|
+
} else if (
|
|
182
|
+
ts.isVariableDeclaration(node) &&
|
|
183
|
+
ts.isIdentifier(node.name) &&
|
|
184
|
+
node.initializer &&
|
|
185
|
+
(ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer))
|
|
186
|
+
) {
|
|
187
|
+
namedFunctions.set(node.name.text, node.initializer);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
return namedFunctions;
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
/** Collects local names of named imports whose module specifier matches `modules`. */
|
|
194
|
+
const collectNamedImportsFrom = ({
|
|
195
|
+
sourceFile,
|
|
196
|
+
modules,
|
|
197
|
+
namePattern,
|
|
198
|
+
}: {
|
|
199
|
+
sourceFile: ts.SourceFile;
|
|
200
|
+
modules: readonly string[];
|
|
201
|
+
namePattern?: RegExp;
|
|
202
|
+
}): Set<string> => {
|
|
203
|
+
const names = new Set<string>();
|
|
204
|
+
if (modules.length === 0) {
|
|
205
|
+
return names;
|
|
206
|
+
}
|
|
207
|
+
for (const statement of sourceFile.statements) {
|
|
208
|
+
if (
|
|
209
|
+
!ts.isImportDeclaration(statement) ||
|
|
210
|
+
!ts.isStringLiteral(statement.moduleSpecifier) ||
|
|
211
|
+
!specifierMatchesModule({modules, specifier: statement.moduleSpecifier.text})
|
|
212
|
+
) {
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const bindings = statement.importClause?.namedBindings;
|
|
216
|
+
if (!bindings || !ts.isNamedImports(bindings)) {
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
for (const element of bindings.elements) {
|
|
220
|
+
if (!namePattern || namePattern.test(element.name.text)) {
|
|
221
|
+
names.add(element.name.text);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return names;
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
interface RuleContext {
|
|
229
|
+
sourceFile: ts.SourceFile;
|
|
230
|
+
config: HygieneRuleConfig;
|
|
231
|
+
/** Root-relative POSIX path of the file under check. */
|
|
232
|
+
relativeFile: string;
|
|
233
|
+
mockHelperNames: Set<string>;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Whether `fn` transitively (through same-file named functions) calls `mock.module()` or a helper. */
|
|
237
|
+
const createMockRegistrationDetector = ({
|
|
238
|
+
sourceFile,
|
|
239
|
+
mockHelperNames,
|
|
240
|
+
}: {
|
|
241
|
+
sourceFile: ts.SourceFile;
|
|
242
|
+
mockHelperNames: Set<string>;
|
|
243
|
+
}): ((fn: ts.FunctionLikeDeclaration) => boolean) => {
|
|
244
|
+
const namedFunctions = collectNamedFunctions(sourceFile);
|
|
245
|
+
const memo = new Map<ts.FunctionLikeDeclaration, boolean>();
|
|
246
|
+
const visiting = new Set<ts.FunctionLikeDeclaration>();
|
|
247
|
+
|
|
248
|
+
const registersMock = (fn: ts.FunctionLikeDeclaration): boolean => {
|
|
249
|
+
const cached = memo.get(fn);
|
|
250
|
+
if (cached !== undefined) {
|
|
251
|
+
return cached;
|
|
252
|
+
}
|
|
253
|
+
if (visiting.has(fn)) {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
visiting.add(fn);
|
|
257
|
+
let found = false;
|
|
258
|
+
const visit = (node: ts.Node): void => {
|
|
259
|
+
if (found) {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (isMockModuleCall(node)) {
|
|
263
|
+
found = true;
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
|
|
267
|
+
const name = node.expression.text;
|
|
268
|
+
const target = namedFunctions.get(name);
|
|
269
|
+
if (mockHelperNames.has(name) || (target && registersMock(target))) {
|
|
270
|
+
found = true;
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
ts.forEachChild(node, visit);
|
|
275
|
+
};
|
|
276
|
+
visit(fn.body ?? fn);
|
|
277
|
+
visiting.delete(fn);
|
|
278
|
+
memo.set(fn, found);
|
|
279
|
+
return found;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
return registersMock;
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
const findModuleScopeMockViolations = ({
|
|
286
|
+
sourceFile,
|
|
287
|
+
mockHelperNames,
|
|
288
|
+
}: RuleContext): HygieneViolation[] => {
|
|
289
|
+
const namedFunctions = collectNamedFunctions(sourceFile);
|
|
290
|
+
const registersMock = createMockRegistrationDetector({mockHelperNames, sourceFile});
|
|
291
|
+
const violations: HygieneViolation[] = [];
|
|
292
|
+
walk(sourceFile, (node) => {
|
|
293
|
+
if (!ts.isCallExpression(node) || !isAtModuleScope(node)) {
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (isMockModuleCallee(node.expression)) {
|
|
297
|
+
violations.push(
|
|
298
|
+
makeViolation({
|
|
299
|
+
message:
|
|
300
|
+
"mock.module() executes at module load; wrap it in a helper called from beforeEach/beforeAll/describe.",
|
|
301
|
+
node,
|
|
302
|
+
ruleId: "no-module-scope-mock-module",
|
|
303
|
+
sourceFile,
|
|
304
|
+
})
|
|
305
|
+
);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
if (!ts.isIdentifier(node.expression)) {
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const name = node.expression.text;
|
|
312
|
+
if (mockHelperNames.has(name)) {
|
|
313
|
+
violations.push(
|
|
314
|
+
makeViolation({
|
|
315
|
+
message: `${name}() registers mock.module() and is invoked at module scope; call it from beforeEach/beforeAll/describe instead.`,
|
|
316
|
+
node,
|
|
317
|
+
ruleId: "no-module-scope-mock-module",
|
|
318
|
+
sourceFile,
|
|
319
|
+
})
|
|
320
|
+
);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
const target = namedFunctions.get(name);
|
|
324
|
+
if (target && registersMock(target)) {
|
|
325
|
+
violations.push(
|
|
326
|
+
makeViolation({
|
|
327
|
+
message: `${name}() registers mock.module() and is invoked at module scope; call it from beforeEach/beforeAll/describe instead.`,
|
|
328
|
+
node,
|
|
329
|
+
ruleId: "no-module-scope-mock-module",
|
|
330
|
+
sourceFile,
|
|
331
|
+
})
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
return violations;
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
const findDirectBarrelMockViolations = ({
|
|
339
|
+
sourceFile,
|
|
340
|
+
config,
|
|
341
|
+
relativeFile,
|
|
342
|
+
}: RuleContext): HygieneViolation[] => {
|
|
343
|
+
if (matchesAnyGlob({filePath: relativeFile, globs: config.barrelMockAllowlist ?? []})) {
|
|
344
|
+
return [];
|
|
345
|
+
}
|
|
346
|
+
const violations: HygieneViolation[] = [];
|
|
347
|
+
walk(sourceFile, (node) => {
|
|
348
|
+
if (!isMockModuleCall(node)) {
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
const [specifierArg] = node.arguments;
|
|
352
|
+
if (
|
|
353
|
+
specifierArg &&
|
|
354
|
+
ts.isStringLiteralLike(specifierArg) &&
|
|
355
|
+
resolvesToBarrel({config, fromFile: sourceFile.fileName, specifier: specifierArg.text})
|
|
356
|
+
) {
|
|
357
|
+
violations.push(
|
|
358
|
+
makeViolation({
|
|
359
|
+
message: `mock.module("${specifierArg.text}") targets a shared barrel directly; use a helper that registers every specifier the barrel resolves under.`,
|
|
360
|
+
node,
|
|
361
|
+
ruleId: "no-direct-barrel-mock",
|
|
362
|
+
sourceFile,
|
|
363
|
+
})
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
return violations;
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
/** Whether `node` is `setTimeout(resolve, N)` (optionally as a statement or return value). */
|
|
371
|
+
const isSetTimeoutOnResolve = ({
|
|
372
|
+
node,
|
|
373
|
+
resolveName,
|
|
374
|
+
}: {
|
|
375
|
+
node: ts.Node;
|
|
376
|
+
resolveName: string;
|
|
377
|
+
}): boolean => {
|
|
378
|
+
let expr: ts.Node = node;
|
|
379
|
+
if (ts.isExpressionStatement(node)) {
|
|
380
|
+
expr = node.expression;
|
|
381
|
+
} else if (ts.isReturnStatement(node) && node.expression) {
|
|
382
|
+
expr = node.expression;
|
|
383
|
+
}
|
|
384
|
+
if (
|
|
385
|
+
!ts.isCallExpression(expr) ||
|
|
386
|
+
!ts.isIdentifier(expr.expression) ||
|
|
387
|
+
expr.expression.text !== "setTimeout"
|
|
388
|
+
) {
|
|
389
|
+
return false;
|
|
390
|
+
}
|
|
391
|
+
const [firstArg] = expr.arguments;
|
|
392
|
+
return Boolean(firstArg && ts.isIdentifier(firstArg) && firstArg.text === resolveName);
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
/** Whether `node` is `new Promise((resolve) => setTimeout(resolve, N))` with no other logic. */
|
|
396
|
+
const isBareSleepPromise = (node: ts.Node): boolean => {
|
|
397
|
+
if (
|
|
398
|
+
!ts.isNewExpression(node) ||
|
|
399
|
+
!ts.isIdentifier(node.expression) ||
|
|
400
|
+
node.expression.text !== "Promise"
|
|
401
|
+
) {
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
const [executor] = node.arguments ?? [];
|
|
405
|
+
if (!executor || !(ts.isArrowFunction(executor) || ts.isFunctionExpression(executor))) {
|
|
406
|
+
return false;
|
|
407
|
+
}
|
|
408
|
+
const [resolveParam] = executor.parameters;
|
|
409
|
+
if (!resolveParam || !ts.isIdentifier(resolveParam.name)) {
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
const statements: readonly ts.Node[] = ts.isBlock(executor.body)
|
|
413
|
+
? executor.body.statements
|
|
414
|
+
: [executor.body];
|
|
415
|
+
return (
|
|
416
|
+
statements.length === 1 &&
|
|
417
|
+
isSetTimeoutOnResolve({node: statements[0], resolveName: resolveParam.name.text})
|
|
418
|
+
);
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
/** Returns `a.b.c` for identifier/property-access callees, otherwise undefined. */
|
|
422
|
+
const getCalleeText = (expr: ts.Expression): string | undefined => {
|
|
423
|
+
if (ts.isIdentifier(expr)) {
|
|
424
|
+
return expr.text;
|
|
425
|
+
}
|
|
426
|
+
if (ts.isPropertyAccessExpression(expr)) {
|
|
427
|
+
const left = getCalleeText(expr.expression);
|
|
428
|
+
return left ? `${left}.${expr.name.text}` : undefined;
|
|
429
|
+
}
|
|
430
|
+
return undefined;
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
const findSleepViolations = ({sourceFile, config}: RuleContext): HygieneViolation[] => {
|
|
434
|
+
const sleepCallees = new Set(config.sleepCallees ?? DEFAULT_SLEEP_CALLEES);
|
|
435
|
+
const violations: HygieneViolation[] = [];
|
|
436
|
+
walk(sourceFile, (node) => {
|
|
437
|
+
if (isBareSleepPromise(node)) {
|
|
438
|
+
violations.push(
|
|
439
|
+
makeViolation({
|
|
440
|
+
message: "Bare setTimeout sleep; poll the actual condition (e.g. waitFor) instead.",
|
|
441
|
+
node,
|
|
442
|
+
ruleId: "no-sleep",
|
|
443
|
+
sourceFile,
|
|
444
|
+
})
|
|
445
|
+
);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
if (!ts.isCallExpression(node)) {
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
const callee = getCalleeText(node.expression);
|
|
452
|
+
if (callee && sleepCallees.has(callee)) {
|
|
453
|
+
violations.push(
|
|
454
|
+
makeViolation({
|
|
455
|
+
message: `${callee}() sleeps for a fixed time; poll the actual condition (e.g. waitFor) instead.`,
|
|
456
|
+
node,
|
|
457
|
+
ruleId: "no-sleep",
|
|
458
|
+
sourceFile,
|
|
459
|
+
})
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
});
|
|
463
|
+
return violations;
|
|
464
|
+
};
|
|
465
|
+
|
|
466
|
+
/** Whether a string/template/concatenation expression contains a literal `?`. */
|
|
467
|
+
const containsQuestionMark = (node: ts.Expression): boolean => {
|
|
468
|
+
if (ts.isStringLiteralLike(node)) {
|
|
469
|
+
return node.text.includes("?");
|
|
470
|
+
}
|
|
471
|
+
if (ts.isTemplateExpression(node)) {
|
|
472
|
+
return (
|
|
473
|
+
node.head.text.includes("?") ||
|
|
474
|
+
node.templateSpans.some((span) => span.literal.text.includes("?"))
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
if (ts.isBinaryExpression(node)) {
|
|
478
|
+
return containsQuestionMark(node.left) || containsQuestionMark(node.right);
|
|
479
|
+
}
|
|
480
|
+
if (ts.isParenthesizedExpression(node)) {
|
|
481
|
+
return containsQuestionMark(node.expression);
|
|
482
|
+
}
|
|
483
|
+
return false;
|
|
484
|
+
};
|
|
485
|
+
|
|
486
|
+
const isDynamicImportCall = (node: ts.Node): node is ts.CallExpression =>
|
|
487
|
+
ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword;
|
|
488
|
+
|
|
489
|
+
const isRequireCall = (node: ts.Node): node is ts.CallExpression =>
|
|
490
|
+
ts.isCallExpression(node) &&
|
|
491
|
+
ts.isIdentifier(node.expression) &&
|
|
492
|
+
node.expression.text === "require";
|
|
493
|
+
|
|
494
|
+
const findCacheBustedImportViolations = ({sourceFile}: RuleContext): HygieneViolation[] => {
|
|
495
|
+
const violations: HygieneViolation[] = [];
|
|
496
|
+
walk(sourceFile, (node) => {
|
|
497
|
+
if (!isDynamicImportCall(node)) {
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
const [arg] = node.arguments;
|
|
501
|
+
if (arg && containsQuestionMark(arg)) {
|
|
502
|
+
violations.push(
|
|
503
|
+
makeViolation({
|
|
504
|
+
message:
|
|
505
|
+
"Dynamic import specifier contains a cache-busting '?'; module identity must stay stable for mock.module to apply.",
|
|
506
|
+
node,
|
|
507
|
+
ruleId: "no-cache-busted-import",
|
|
508
|
+
sourceFile,
|
|
509
|
+
})
|
|
510
|
+
);
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
return violations;
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
const getMockFactory = ({
|
|
517
|
+
node,
|
|
518
|
+
mockHelperNames,
|
|
519
|
+
}: {
|
|
520
|
+
node: ts.Node;
|
|
521
|
+
mockHelperNames: Set<string>;
|
|
522
|
+
}): ts.ArrowFunction | ts.FunctionExpression | undefined => {
|
|
523
|
+
let factory: ts.Expression | undefined;
|
|
524
|
+
if (isMockModuleCall(node)) {
|
|
525
|
+
factory = node.arguments[1];
|
|
526
|
+
} else if (
|
|
527
|
+
ts.isCallExpression(node) &&
|
|
528
|
+
ts.isIdentifier(node.expression) &&
|
|
529
|
+
mockHelperNames.has(node.expression.text)
|
|
530
|
+
) {
|
|
531
|
+
factory = node.arguments[0];
|
|
532
|
+
}
|
|
533
|
+
if (factory && (ts.isArrowFunction(factory) || ts.isFunctionExpression(factory))) {
|
|
534
|
+
return factory;
|
|
535
|
+
}
|
|
536
|
+
return undefined;
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
const findLateRealCaptureViolations = ({
|
|
540
|
+
sourceFile,
|
|
541
|
+
config,
|
|
542
|
+
mockHelperNames,
|
|
543
|
+
}: RuleContext): HygieneViolation[] => {
|
|
544
|
+
const getterNames = collectNamedImportsFrom({
|
|
545
|
+
modules: config.realExportGetterModules ?? [],
|
|
546
|
+
namePattern: config.realExportGetterNamePattern
|
|
547
|
+
? new RegExp(config.realExportGetterNamePattern, "u")
|
|
548
|
+
: undefined,
|
|
549
|
+
sourceFile,
|
|
550
|
+
});
|
|
551
|
+
const violations: HygieneViolation[] = [];
|
|
552
|
+
const checkFactoryNode = (node: ts.Node): void => {
|
|
553
|
+
if (isRequireCall(node) || isDynamicImportCall(node)) {
|
|
554
|
+
const [specifierArg] = node.arguments;
|
|
555
|
+
if (
|
|
556
|
+
specifierArg &&
|
|
557
|
+
ts.isStringLiteralLike(specifierArg) &&
|
|
558
|
+
resolvesToBarrel({config, fromFile: sourceFile.fileName, specifier: specifierArg.text})
|
|
559
|
+
) {
|
|
560
|
+
violations.push(
|
|
561
|
+
makeViolation({
|
|
562
|
+
message: `Captures the real "${specifierArg.text}" barrel inside a mock factory; capture it at module scope before mock registration instead.`,
|
|
563
|
+
node,
|
|
564
|
+
ruleId: "no-late-real-capture",
|
|
565
|
+
sourceFile,
|
|
566
|
+
})
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
if (
|
|
572
|
+
ts.isCallExpression(node) &&
|
|
573
|
+
ts.isIdentifier(node.expression) &&
|
|
574
|
+
getterNames.has(node.expression.text)
|
|
575
|
+
) {
|
|
576
|
+
violations.push(
|
|
577
|
+
makeViolation({
|
|
578
|
+
message: `Calls ${node.expression.text}() inside a mock factory; call it at module scope before mock registration instead.`,
|
|
579
|
+
node,
|
|
580
|
+
ruleId: "no-late-real-capture",
|
|
581
|
+
sourceFile,
|
|
582
|
+
})
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
walk(sourceFile, (node) => {
|
|
587
|
+
const factory = getMockFactory({mockHelperNames, node});
|
|
588
|
+
if (factory) {
|
|
589
|
+
walk(factory.body, checkFactoryNode);
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
return violations;
|
|
593
|
+
};
|
|
594
|
+
|
|
595
|
+
const addBindingNames = ({name, out}: {name: ts.BindingName; out: Set<string>}): void => {
|
|
596
|
+
if (ts.isIdentifier(name)) {
|
|
597
|
+
out.add(name.text);
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
for (const element of name.elements) {
|
|
601
|
+
if (ts.isBindingElement(element)) {
|
|
602
|
+
addBindingNames({name: element.name, out});
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
/** Names bound to module imports: static imports plus `const {X} = await import()/require()`. */
|
|
608
|
+
const collectImportedNames = (sourceFile: ts.SourceFile): Set<string> => {
|
|
609
|
+
const importedNames = new Set<string>();
|
|
610
|
+
walk(sourceFile, (node) => {
|
|
611
|
+
if (ts.isImportDeclaration(node) && node.importClause) {
|
|
612
|
+
const {importClause} = node;
|
|
613
|
+
if (importClause.name) {
|
|
614
|
+
importedNames.add(importClause.name.text);
|
|
615
|
+
}
|
|
616
|
+
const bindings = importClause.namedBindings;
|
|
617
|
+
if (bindings && ts.isNamedImports(bindings)) {
|
|
618
|
+
for (const element of bindings.elements) {
|
|
619
|
+
importedNames.add(element.name.text);
|
|
620
|
+
}
|
|
621
|
+
} else if (bindings && ts.isNamespaceImport(bindings)) {
|
|
622
|
+
importedNames.add(bindings.name.text);
|
|
623
|
+
}
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
if (ts.isVariableDeclaration(node) && node.initializer) {
|
|
627
|
+
const init = ts.isAwaitExpression(node.initializer)
|
|
628
|
+
? node.initializer.expression
|
|
629
|
+
: node.initializer;
|
|
630
|
+
if (isDynamicImportCall(init) || isRequireCall(init)) {
|
|
631
|
+
addBindingNames({name: node.name, out: importedNames});
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
});
|
|
635
|
+
return importedNames;
|
|
636
|
+
};
|
|
637
|
+
|
|
638
|
+
const findComponentSnapshotViolations = ({sourceFile}: RuleContext): HygieneViolation[] => {
|
|
639
|
+
const importedNames = collectImportedNames(sourceFile);
|
|
640
|
+
const violations: HygieneViolation[] = [];
|
|
641
|
+
walk(sourceFile, (node) => {
|
|
642
|
+
if (
|
|
643
|
+
!ts.isCallExpression(node) ||
|
|
644
|
+
!ts.isPropertyAccessExpression(node.expression) ||
|
|
645
|
+
node.expression.name.text !== "toMatchSnapshot"
|
|
646
|
+
) {
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
const receiver = node.expression.expression;
|
|
650
|
+
if (
|
|
651
|
+
!ts.isCallExpression(receiver) ||
|
|
652
|
+
!ts.isIdentifier(receiver.expression) ||
|
|
653
|
+
receiver.expression.text !== "expect"
|
|
654
|
+
) {
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
const [arg] = receiver.arguments;
|
|
658
|
+
if (arg && ts.isIdentifier(arg) && importedNames.has(arg.text)) {
|
|
659
|
+
violations.push(
|
|
660
|
+
makeViolation({
|
|
661
|
+
message: `expect(${arg.text}).toMatchSnapshot() snapshots the imported reference, not rendered output; render it first.`,
|
|
662
|
+
node,
|
|
663
|
+
ruleId: "no-component-snapshot",
|
|
664
|
+
sourceFile,
|
|
665
|
+
})
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
});
|
|
669
|
+
return violations;
|
|
670
|
+
};
|
|
671
|
+
|
|
672
|
+
const RULES: Record<HygieneRuleId, (context: RuleContext) => HygieneViolation[]> = {
|
|
673
|
+
"no-cache-busted-import": findCacheBustedImportViolations,
|
|
674
|
+
"no-component-snapshot": findComponentSnapshotViolations,
|
|
675
|
+
"no-direct-barrel-mock": findDirectBarrelMockViolations,
|
|
676
|
+
"no-late-real-capture": findLateRealCaptureViolations,
|
|
677
|
+
"no-module-scope-mock-module": findModuleScopeMockViolations,
|
|
678
|
+
"no-sleep": findSleepViolations,
|
|
679
|
+
};
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* Runs the enabled rules against one parsed file. Pure and filesystem free. Returned violations
|
|
683
|
+
* carry the root-relative path and are not yet suppression filtered.
|
|
684
|
+
*/
|
|
685
|
+
export const runHygieneRules = ({
|
|
686
|
+
fileName,
|
|
687
|
+
sourceText,
|
|
688
|
+
config,
|
|
689
|
+
rules = HYGIENE_RULE_IDS,
|
|
690
|
+
}: {
|
|
691
|
+
/** Absolute path, used for relative-specifier resolution and reported paths. */
|
|
692
|
+
fileName: string;
|
|
693
|
+
sourceText: string;
|
|
694
|
+
config: HygieneRuleConfig;
|
|
695
|
+
rules?: readonly HygieneRuleId[];
|
|
696
|
+
}): {violations: HygieneViolation[]} => {
|
|
697
|
+
const isJsx = /\.[jt]sx$/u.test(fileName);
|
|
698
|
+
const sourceFile = ts.createSourceFile(
|
|
699
|
+
fileName,
|
|
700
|
+
sourceText,
|
|
701
|
+
ts.ScriptTarget.Latest,
|
|
702
|
+
true,
|
|
703
|
+
isJsx ? ts.ScriptKind.TSX : ts.ScriptKind.TS
|
|
704
|
+
);
|
|
705
|
+
const context: RuleContext = {
|
|
706
|
+
config,
|
|
707
|
+
mockHelperNames: collectNamedImportsFrom({
|
|
708
|
+
modules: config.mockHelperModules ?? [],
|
|
709
|
+
sourceFile,
|
|
710
|
+
}),
|
|
711
|
+
relativeFile: toPosixPath(path.relative(config.rootDir, fileName)),
|
|
712
|
+
sourceFile,
|
|
713
|
+
};
|
|
714
|
+
const violations = rules
|
|
715
|
+
.flatMap((ruleId) => RULES[ruleId](context))
|
|
716
|
+
.map((violation) => ({...violation, file: context.relativeFile}))
|
|
717
|
+
.sort((a, b) => a.line - b.line || a.ruleId.localeCompare(b.ruleId));
|
|
718
|
+
return {violations};
|
|
719
|
+
};
|