testVitestInChrome

tcmts.cli.test.e2e.vitest.testVitestInChrome · #oisabudy · term

Vitest: a test that renders a component with state runs in Chrome, and reaches server functions by hash.

import { CHROME } from "#codebase/tcmts/cli/test/browser";
import { setUp } from "#codebase/tcmts/cli/test/e2e/vitest";
import assert from "node:assert/strict";

export const testVitestInChrome = () => {
  if (!CHROME) return console.log("skipped: no Chrome");
  const { tcm, write } = setUp();
  write(
    "ui.tsx",
    `// tcm: namespace ui\nimport { hostname } from "node:os";\nimport { useEffect, useState } from "react";\nimport { expect } from "vitest";\n` +
      `import { fireEvent, render, screen, waitFor } from "@testing-library/react";\n\n` +
      `export async function serverName(): Promise<string> {\n  return hostname() ? "a server" : "?";\n}\n\n` +
      `export function Counter() {\n  const [n, setN] = useState(0);\n  const [name, setName] = useState("…");\n  useEffect(() => void serverName().then(setName), []);\n` +
      `  return <button onClick={() => setN(n + 1)}>clicked {n} on {name}</button>;\n}\n\n` +
      `export const testCounter = async () => {\n  render(<Counter />);\n  fireEvent.click(screen.getByRole("button"));\n` +
      `  await waitFor(() => expect(screen.getByRole("button").textContent).toBe("clicked 1 on a server"));\n  expect(typeof window).toBe("object");\n};\n\n` +
      `export const testInNode = () => {\n  expect(typeof process.versions.node).toBe("string");\n};\n`,
  );
  // checked before it's saved: the scratch file's own definitions are what the test runs
  const checked = tcm("check", "ui.tsx");
  assert.match(checked, /✓ ui\.testCounter/, "in a browser: it renders a component that keeps state");
  assert.match(checked, /✓ ui\.testInNode/, "and a test that doesn't need one runs in Node");
}

uses