Skip to content

Commit

Permalink
fix(codemod): support aliased act() import
Browse files Browse the repository at this point in the history
  • Loading branch information
henryqdineen committed Aug 16, 2024
1 parent 724b5a5 commit eaefbc8
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { act as reactAct } from "react-dom/test-utils";

reactAct();
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { act as reactAct } from "react";

reactAct();
14 changes: 8 additions & 6 deletions packages/codemods/react/19/replace-act-import/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,12 @@ export default function transform(
specifiers: [{ type: "ImportSpecifier", imported: { name: "act" } }],
})
.forEach((path) => {
const newImportSpecifier = j.importSpecifier(
j.identifier("act"),
j.identifier("act"),
);
const actSpecifiers =
path.node.specifiers?.filter(
(specifier) =>
j.ImportSpecifier.check(specifier) &&
specifier.imported.name === "act",
) ?? [];

const existingReactImportCollection = root.find(j.ImportDeclaration, {
source: { value: "react" },
Expand All @@ -111,13 +113,13 @@ export default function transform(
existingReactImportCollection
.paths()
.at(0)
?.node.specifiers?.push(newImportSpecifier);
?.node.specifiers?.push(...actSpecifiers);

path.prune();
isDirty = true;
} else {
const newImportDeclaration = j.importDeclaration(
[newImportSpecifier],
actSpecifiers,
j.literal("react"),
);

Expand Down
25 changes: 25 additions & 0 deletions packages/codemods/react/19/replace-act-import/test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,4 +215,29 @@ describe("react/19/replace-act-import: TestUtils.act -> React.act", () => {
OUTPUT.replace(/\W/gm, ""),
);
});

it("should preserve aliased import specifier name", async () => {
const INPUT = await readFile(
join(__dirname, "..", "__testfixtures__/aliased-import.input.js"),
"utf-8",
);
const OUTPUT = await readFile(
join(__dirname, "..", "__testfixtures__/aliased-import.output.js"),
"utf-8",
);

const fileInfo: FileInfo = {
path: "index.ts",
source: INPUT,
};

const actualOutput = transform(fileInfo, buildApi("js"), {
quote: "single",
});

assert.deepEqual(
actualOutput?.replace(/\W/gm, ""),
OUTPUT.replace(/\W/gm, ""),
);
});
});

0 comments on commit eaefbc8

Please sign in to comment.