Skip to content

Commit

Permalink
perf: don't collect more info than needed when resolving jest functions
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Rath committed Nov 4, 2022
1 parent 9658dbb commit 7ef51c1
Showing 1 changed file with 35 additions and 8 deletions.
43 changes: 35 additions & 8 deletions src/rules/utils/parseJestFnCall.ts
Expand Up @@ -550,6 +550,37 @@ const collectReferences = (scope: TSESLint.Scope.Scope) => {
return { locals, imports, unresolved };
};

const resolveScope = (
scope: TSESLint.Scope.Scope,
identifier: string | null = null,
) => {
let currentScope: TSESLint.Scope.Scope | null = scope;

while (currentScope !== null) {
for (const ref of currentScope.variables) {
if (ref.defs.length === 0) {
continue;
}

const def = ref.defs[ref.defs.length - 1];

const importDetails = describePossibleImportDef(def);

if (importDetails?.local === identifier) {
return importDetails;
}

if (ref.name === identifier) {
return 'local';
}
}

currentScope = currentScope.upper;
}

return null;
};

interface ResolvedJestFn {
original: string | null;
local: string;
Expand All @@ -560,9 +591,11 @@ const resolveToJestFn = (
context: TSESLint.RuleContext<string, unknown[]>,
identifier: string,
): ResolvedJestFn | null => {
const references = collectReferences(context.getScope());
const maybeImport = resolveScope(context.getScope(), identifier);

const maybeImport = references.imports.get(identifier);
if (maybeImport === 'local') {
return null;
}

if (maybeImport) {
// the identifier is imported from @jest/globals,
Expand All @@ -578,12 +611,6 @@ const resolveToJestFn = (
return null;
}

// the identifier was found as a local variable or function declaration
// meaning it's not a function from jest
if (references.locals.has(identifier)) {
return null;
}

return {
original: resolvePossibleAliasedGlobal(identifier, context),
local: identifier,
Expand Down

0 comments on commit 7ef51c1

Please sign in to comment.