Skip to content

Commit

Permalink
fix(prefer-importing-jest-globals): give commonjs and esmodules the s…
Browse files Browse the repository at this point in the history
…ame import behaviour
  • Loading branch information
ezimmer-atlassian committed Sep 2, 2024
1 parent 0f41ddc commit f33e4d9
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 26 deletions.
10 changes: 5 additions & 5 deletions src/rules/__tests__/prefer-importing-jest-globals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,11 +304,11 @@ ruleTester.run('prefer-importing-jest-globals', rule, {
`,
// todo: this shouldn't be indenting the "test"
output: dedent`
const { expect, test } = require('@jest/globals');
const source = 'globals';
const {describe} = require(\`@jest/\${source}\`);
describe("suite", () => {
const { expect, test } = require('@jest/globals');
test("foo");
test("foo");
expect(true).toBeDefined();
})
`,
Expand Down Expand Up @@ -407,8 +407,8 @@ ruleTester.run('prefer-importing-jest-globals', rule, {
});
`,
output: dedent`
const { pending } = require('actions');
const { describe, test } = require('@jest/globals');
const { pending } = require('actions');
describe('foo', () => {
test.each(['hello', 'world'])("%s", (a) => {});
});
Expand Down Expand Up @@ -552,12 +552,12 @@ ruleTester.run('prefer-importing-jest-globals', rule, {
const onClick = jest.fn();
describe("suite", () => {
test("foo");
expect(onClick).toHaveBeenCalled();
expect(onClick).toHaveBeenCalled();
})
`,
output: dedent`
console.log('hello');
const { describe, expect, jest, test } = require('@jest/globals');
console.log('hello');
const onClick = jest.fn();
describe("suite", () => {
test("foo");
Expand Down
22 changes: 1 addition & 21 deletions src/rules/prefer-importing-jest-globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,6 @@ 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 @@ -167,12 +151,8 @@ export default createRule({
);

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

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

0 comments on commit f33e4d9

Please # to comment.