Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pageTranslationGuard.browser.test.tsx

42 lines1.6 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import { render } from "../../test/render";
4import { guardDomAgainstPageTranslation } from "./pageTranslationGuard";
5​
6// What Chrome's page translator does: swap each text node for <font><font>translation</font></font>.
7function translatePage(root: Element) {
8 const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
9 const textNodes: Text[] = [];
10 while (walker.nextNode()) textNodes.push(walker.currentNode as Text);
11 for (const text of textNodes) {
12 if (!text.nodeValue?.trim()) continue;
13 const outer = document.createElement("font");
14 const inner = document.createElement("font");
15 inner.textContent = `译:${text.nodeValue}`;
16 outer.append(inner);
17 text.replaceWith(outer);
18 }
20​
21function Status({ running }: { running: boolean }) {
22 return (
23 <div>
24 {running ? "Working" : <i data-testid="done" />}
25 {"for 2s"}
26 </div>
27 );
29​
30describe("guardDomAgainstPageTranslation", () => {
31 it("keeps React committing after page translation replaced its text nodes", async () => {
32 guardDomAgainstPageTranslation();
33 await using screen = await render(<Status running />, { router: false });
34 translatePage(screen.container);
35​
36 // Removing "Working" hits removeChild; placing the icon before "for 2s" hits insertBefore.
37 await screen.rerender(<Status running={false} />);
38 await expect.element(screen.getByTestId("done")).toBeInTheDocument();
39 await screen.rerender(<Status running />);
40 await expect.element(screen.getByTestId("done")).not.toBeInTheDocument();
41 });
42});