testWrittenOutCodeLeavesTestsInNode
A test reaching code that writes a browser function's source into a file (${lazyImages}) runs in Node, where
the rest of its code (node:fs) runs: writing the function out doesn't run it. A test that does call a browser
function runs in Chrome, and when it can't load there it says what put it there.
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 testWrittenOutCodeLeavesTestsInNode = () => { const { tcm, run, write } = setUp(); write( "gen.ts", `// tcm: namespace gen import { readFileSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; /** runs in the page the generated file is loaded into */ export function lazyImages(root: object) { new IntersectionObserver(() => {}).observe(root as never); } export function writeRuntime(dir: string): string { const file = path.join(dir, "runtime.js"); writeFileSync(file, \`(\${lazyImages})(document.body);\\n\`); return readFileSync(file, "utf8"); } export const testWritesTheRuntime = () => { const text = writeRuntime(os.tmpdir()); if (!text.includes("new IntersectionObserver")) throw new Error(text); }; `, ); tcm("add", "gen.ts"); const ran = run("test", "gen"); assert.match(ran.out, /✓ gen\.testWritesTheRuntime/, `in Node:\n${ran.out}`); assert.match( tcm("view", "gen.writeRuntime"), /runs on the server: it uses node:\w+\n/, "and nowhere else", ); assert.match(tcm("view", "gen.lazyImages"), /runs in the browser: it uses IntersectionObserver/); if (!CHROME) return console.log("skipped the browser half: no Chrome"); write( "both.ts", `// tcm: namespace both import { lazyImages } from "#codebase/gen"; import { existsSync } from "node:fs"; export const testObservesWhereFilesAre = () => { if (!existsSync("/")) lazyImages({}); }; `, ); tcm("add", "both.ts"); const { status, out } = run("test", "both"); assert.notEqual(status, 0, out); assert.match( out, /runs in a browser, since it uses gen\.lazyImages, which uses IntersectionObserver/, "it says why the test ran in a browser", ); }