testComponentsAreCompiled

tcmts.cli.test.e2e.react.testComponentsAreCompiled · #vhycfqv5 · term

A component app's components are memoized by React Compiler as it's built (oxc's, installed when it's first needed), in the browser's bundle: and the page works as written

import { CHROME, hydrated, withPage } from "#codebase/tcmts/cli/test/browser";
import { okIn, plainEnv, tcmBin, tempDir, withChildren } from "#codebase/tcmts/cli/test/e2e/harness";
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";

export const testComponentsAreCompiled = () =>
  withChildren(async (keep) => {
    const dir = tempDir("react compiler");
    const tcm = (...args: string[]) => okIn(dir, ...args);
    tcm("init");
    fs.rmSync(path.join(dir, "scratch.ts"));
    fs.writeFileSync(
      path.join(dir, "count.tsx"),
      `// tcm: namespace count
import { useState } from "react";

export function Item({ n }: { n: number }) {
  return <li>{n * 2}</li>;
}

export function App() {
  const [n, setN] = useState(1);
  const items = [1, 2, 3].map((i) => i + n);
  return (
    <main>
      <button onClick={() => setN(n + 1)}>{n}</button>
      <ul>{items.map((i) => <Item key={i} n={i} />)}</ul>
    </main>
  );
}
`,
    );
    tcm("add", "count.tsx");
    tcm("build", "count.App");
    const assets = path.join(dir, ".tcm", "apps", "assets");
    const code = fs
      .readdirSync(assets)
      .filter((f) => /^app-.*\.js$/.test(f))
      .map((f) => fs.readFileSync(path.join(assets, f), "utf8"))
      .join("\n");
    assert.match(code, /react\.memo_cache_sentinel/, "memoized by React Compiler");
    if (!CHROME) return console.log("skipped the browser: no Chrome");
    const url = await new Promise<string>((resolve, reject) => {
      const child = keep(
        spawn(process.execPath, [tcmBin(), "start", "count.App", "--port", "0"], {
          cwd: dir,
          env: plainEnv(),
        }),
      );
      let out = "";
      child.stdout.setEncoding("utf8").on("data", (d: string) => {
        out += d;
        const m = /url\s+(http:\/\/\S+)/.exec(out);
        if (m) resolve(m[1]!);
      });
      child.on("exit", (c) => reject(new Error(`tcm start exited ${c}:\n${out}`)));
    });
    await withPage(url, async (p) => {
      assert.ok(await hydrated(p));
      assert.equal(await p.evaluate(`document.querySelector("ul").textContent`), "468");
      await p.evaluate(`document.querySelector("button").click()`);
      assert.equal(
        await p.waitFor<string>(`document.querySelector("ul").textContent`, (t) => t === "6810"),
        "6810",
      );
      assert.deepEqual(p.errors, []);
    });
  })

uses