testDomTypesLeaveTestsInNode

tcmts.cli.test.e2e.vitest.testDomTypesLeaveTestsInNode · #hbn7av2o · term

A test whose code names DOM types only as types (el: Element, as HTMLElement, Array<Node>) runs in Node, where the rest of its code (node:fs) runs: types are erased, so they don't need a browser.

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

export const testDomTypesLeaveTestsInNode = () => {
  const { tcm, run, write } = setUp();
  write(
    "measure.ts",
    `// tcm: namespace measure
import { existsSync } from "node:fs";

export const widthOf = (el: Element) => (el as HTMLElement).offsetWidth;

export function firstOf(nodes: Array<Node>): Node | undefined {
  return nodes[0];
}

export const testMeasuresInNode = () => {
  const el = { offsetWidth: 3 } as unknown as Element;
  if (widthOf(el) !== 3 || firstOf([]) !== undefined || !existsSync("/")) throw new Error("wrong");
};
`,
  );
  tcm("add", "measure.ts");
  const ran = run("test", "measure");
  assert.equal(ran.status, 0, ran.out);
  assert.match(ran.out, /✓ measure\.testMeasuresInNode/, `in Node:\n${ran.out}`);
  assert.match(tcm("view", "measure.widthOf"), /runs anywhere/);
  assert.match(tcm("view", "measure.firstOf"), /runs anywhere/);
  assert.match(tcm("view", "measure.testMeasuresInNode"), /runs on the server: it uses node:fs\n/);
}

uses