Skip to content

Commit

Permalink
fix(prefer-importing-jest-globals): ensure imports aren't inserted in…
Browse files Browse the repository at this point in the history
… the middle of a statement
  • Loading branch information
ezimmer-atlassian committed Aug 30, 2024
1 parent 11ef4fc commit ecec8dc
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 1 deletion.
55 changes: 55 additions & 0 deletions src/rules/__tests__/prefer-importing-jest-globals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -546,5 +546,60 @@ ruleTester.run('prefer-importing-jest-globals', rule, {
},
],
},
{
code: dedent`
console.log('hello');
const onClick = jest.fn();
describe("suite", () => {
test("foo");
expect(onClick).toHaveBeenCalled();
})
`,
output: dedent`
console.log('hello');
const { describe, expect, jest, test } = require('@jest/globals');
const onClick = jest.fn();
describe("suite", () => {
test("foo");
expect(onClick).toHaveBeenCalled();
})
`,
errors: [
{
endColumn: 21,
column: 17,
line: 2,
messageId: 'preferImportingJestGlobal',
},
],
},
{
code: dedent`
console.log('hello');
const onClick = jest.fn();
describe("suite", () => {
test("foo");
expect(onClick).toHaveBeenCalled();
})
`,
output: dedent`
import { describe, expect, jest, test } from '@jest/globals';
console.log('hello');
const onClick = jest.fn();
describe("suite", () => {
test("foo");
expect(onClick).toHaveBeenCalled();
})
`,
parserOptions: { sourceType: 'module' },
errors: [
{
endColumn: 21,
column: 17,
line: 2,
messageId: 'preferImportingJestGlobal',
},
],
},
],
});
22 changes: 21 additions & 1 deletion src/rules/prefer-importing-jest-globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,22 @@ const createFixerImports = (
: `const { ${allImportsFormatted} } = require('@jest/globals');`;
};

const findInsertionPoint = (reportingNode: TSESTree.Node) => {
let currentNode = reportingNode;

while (
currentNode.parent &&
currentNode.parent.type !== AST_NODE_TYPES.Program &&
currentNode.parent.type !== AST_NODE_TYPES.VariableDeclaration
) {
currentNode = currentNode.parent;
}

return currentNode.parent?.type === AST_NODE_TYPES.VariableDeclaration
? currentNode.parent
: reportingNode;
};

const allJestFnTypes: JestFnType[] = [
'hook',
'describe',
Expand Down Expand Up @@ -158,8 +174,12 @@ export default createRule({
);

if (requireNode?.type !== AST_NODE_TYPES.VariableDeclaration) {
const insertBeforeNode = isModule
? firstNode
: findInsertionPoint(reportingNode);

return fixer.insertTextBefore(
reportingNode,
insertBeforeNode,
`${createFixerImports(isModule, functionsToImport)}\n`,
);
}
Expand Down

0 comments on commit ecec8dc

Please # to comment.