js-test

0.1.3

A simple framework for testing cxy web applications

Carter Mbotho<lastcarter@gmail.com> MIT 0 downloads Repository

js-test Developer Guide

A practical, example-first guide to writing tests with js-test. If you're new to the framework, read 15 and you'll be productive; the rest is reference by feature.

  • Zero npm. No package.json, no node_modules. Tests run on Node's built-in

node:test and web-standard APIs.

  • Application-agnostic. Test any binary, server, CLI, or rendered page.
  • Hermetic. Every suite gets its own ports, scratch databases, and log

directory.


1. Getting started

Install (in a Cxy project)

Add js-test as a dev dependency in your Cxyfile.yaml:

dev-dependencies:
  - name: js-test
    repository: https://github.com/cxy-lang/js-test.git
    version: '^0.1.0'

Then cxy package install. Because js-test exports its runner, you can run it directly with zero local config:

cxy package run @js-test test

Or add a local shorthand to your Cxyfile.yaml:

scripts:
  test: cxy package run @js-test test -- "$@"
cxy package run test

Run directly (no Cxy)

node path/to/js-test/bin/runner.mjs

The runner discovers tests/**/*.test.mjs (and *.test.js) under the current directory.


2. Your first test

A test file is a normal node:test file that imports from "js-test":

// tests/hello.test.mjs
import test from "node:test";
import assert from "node:assert/strict";
import { findFreePort } from "js-test";

test("allocates a free port", async () => {
    const port = await findFreePort();
    assert.ok(port > 0);
});

Run it:

cxy package run test -- -s hello

The bare "js-test" import works without node_modules the runner registers a module-resolution hook that maps it to the installed package.


3. The runner

node "${CXY_PACKAGE_DIR}/bin/runner.mjs" [options] [files...]
Flag Meaning
-s, --suite <regex> Only run test files whose path matches
-f, --filter <regex> Only run tests whose name matches
`--browser <chromium\ safari>` Browser engine for browser suites (default chromium)
--browser-path <path> Explicit browser binary/driver
--artifacts-dir <path> Where run artifacts go (default .cxy/build/tests)
--stdout <reporter> Stdout reporter: spec tap dot json junit none
`--reporter <name\ path>` Add a file reporter (repeatable) <runDir>/results.<ext>
--config <path> / --no-config Use / skip test.config.mjs
--no-memory Disable Cxy memory analysis
--watch Re-run on file changes
-v, --verbose Verbose diagnostics

Examples:

cxy package run test -- -s auth -f "login"     # auth suite, tests matching "login"
cxy package run test -- --reporter json        # also write results.json
cxy package run test -- --stdout none --reporter tap   # only a results.tap file

4. createSuite the main entry point

Most tests start by creating a suite: it provisions services, starts your server on a free port, and gives you a client plus assertion helpers.

import test from "node:test";
import { createSuite } from "js-test";

test("my API works", async (t) => {
    const suite = await createSuite(t, {
        binary: "./.cxy/build/my-server",
        args: (port) => ["--port", port],
        healthCheck: "/healthz"
    });

    const res = await suite.get("/healthz");
    suite.check("health is 200", 200, res);
});

Passing t as the first argument auto-registers t.after(() => suite.close()), so the server and services are torn down for you.

createSuite options

Option Meaning
name Suite name (used in log filenames)
binary Path to the server under test (optional)
args string[] or (port) => string[]
env Extra environment variables
cwd Working directory
healthCheck "/healthz" or `{ type: "tcp"\ "http", path, timeoutMs, intervalMs }`
services Service[] (see 9)
headers Default request headers
loginPath Path used by suite.login() (default /login)
cli Path to a companion CLI (for suite.cli())
token Default auth token forwarded to the CLI

What you get back

Member Purpose
suite.base / suite.port The running server's URL/port
suite.client The underlying ApiClient
suite.get/post/put/patch/delete/call HTTP requests (5)
suite.check/equals/has/hasnt/jcheck Assertions (6)
suite.bearer(token) / suite.basic(u, p) Auth headers (7)
suite.login(user, pass) Log in, retain cookies (7)
suite.sse(path) / suite.ws(path) Streaming (8)
suite.cli(args, opts) Run a CLI (10)
suite.mockHttp(routes) / suite.mockWs() Mock servers (11)
suite.browser(opts) Browser automation (12)
suite.validateHtml(html, opts) SSR/DOM validation (13)
suite.memory() Cxy memory analysis (16)
suite.reset() / suite.close() Reset services / tear down

5. HTTP requests

const res = await suite.get("/items");
const created = await suite.post("/items", { name: "widget" });
await suite.put("/items/1", { name: "gadget" });
await suite.patch("/items/1", { done: true });
await suite.delete("/items/1");
const custom = await suite.call("POST", "/graphql", { query: "{ me }" });

Bodies are JSON-serialized automatically (and Content-Type is set). Pass extra headers as trailing arguments:

await suite.get("/admin", { "X-Trace": "abc" });

The response object

res.status      // 200
res.ok          // true
res.headers     // Headers
res.text        // raw body
res.body        // alias of text
res.json        // parsed JSON (null if not JSON)
res.url         // final URL

Using ApiClient directly

suite.client is an ApiClient you can use standalone (e.g. against a mock):

import { ApiClient } from "js-test";
const client = new ApiClient({ base: "http://127.0.0.1:3000" });
const res = await client.get("/healthz");

6. Assertions

These produce readable failures and (for response-based ones) archive the full response under the run directory.

suite.check("create returns 201", 201, res);          // status code
suite.equals("role is admin", "admin", res.json.role); // deep equality
suite.has("body mentions widget", "widget", res);      // substring present
suite.hasnt("no stack traces", "Traceback", res);      // substring absent
suite.jcheck("is an array", (j) => Array.isArray(j.items), res); // predicate on JSON

On failure, check/has/hasnt/jcheck write the full response to <runDir>/failures/<name>.txt and include the path in the error.

You can also import them directly:

import { check, equals, has, hasnt, jcheck } from "js-test";

7. Sessions & authentication

The client keeps a cookie jar automatically log in once and subsequent requests carry the session:

const token = await suite.login("admin", "secret");   // POSTs to suite.loginPath
// cookies are retained; token is returned when the response has one

const me = await suite.get("/me");                     // uses the session cookie
suite.jcheck("me is admin", (j) => j.user === "admin", me);

Bearer / Basic auth:

await suite.get("/me", suite.bearer(token));
await suite.get("/me", suite.basic("user", "pass"));

login() returns res.json.token (or access_token) when present, otherwise the response object. Customize the path/body:

await suite.login("admin", "secret", { path: "/api/v1/auth/login", body: { login: "admin", password: "secret" } });

8. Streaming (SSE & WebSockets)

Server-Sent Events

const events = await suite.sse("/events");
const ready = await events.next();                     // first event
const done = await events.waitFor((e) => e.event === "done");
suite.equals("ready payload", "ok", ready.data);
events.close();

Each event is { event, data, id, retry }. next(timeoutMs) and waitFor(predicate, timeoutMs) reject on timeout, so a missing event fails fast.

WebSockets

const ws = suite.ws("/socket");
await ws.open();
ws.send({ type: "subscribe", channel: "builds" });
const msg = await ws.waitFor((m) => m.type === "subscribed");
ws.close();

send() JSON-encodes non-strings; next() returns the raw payload; waitFor(predicate) receives the JSON-parsed value when parseable.

Both suite.sse(path, { headers }) and suite.ws(path, { headers }) accept headers, which is how a Bearer token reaches an authenticated endpoint:

const ws = suite.ws("/api/v1/agent/builds/1/log/ws", { headers: suite.bearer(agentKey) });
const events = await suite.sse("/api/v1/builds/1/events", { headers: suite.bearer(token) });

9. Services (databases, caches, containers)

Declare services in createSuite; their env vars are injected into your server automatically, and they're torn down with the suite.

import { createSuite, PostgresService, RedisService } from "js-test";

const suite = await createSuite(t, {
    binary: "./.cxy/build/my-server",
    services: [
        new PostgresService({
            command: ["docker", "exec", "test-postgres", "psql"],
            user: "postgres",
            seed: ["CREATE TABLE items (id serial primary key, name text not null)"]
        }),
        new RedisService({ db: 15 })
    ]
});

PostgresService

Drives a command prefix (["psql"] or ["docker","exec","<c>","psql"]), so Docker is optional. Creates a scratch DB per suite and drops it on exit.

await pg.exec("INSERT INTO items (name) VALUES ('widget')");
const rows = await pg.query("SELECT name FROM items");   // [{ name: "widget" }]
const count = await pg.scalar("SELECT count(*) FROM items"); // "1"
await pg.exec(pg.sql`INSERT INTO items (name) VALUES (${"gadget's"})`); // safe interpolation
await pg.reset();                                        // truncates public tables

Injects DATABASE_URL (configurable via envVar).

RedisService

A zero-dependency RESP2 client (no redis-cli).

await redis.command("SET", "k", "v");
const v = await redis.command("GET", "k");
await redis.flushdb();     // or await redis.reset()

Injects REDIS_URL.

SqliteService

File-backed scratch DB on node:sqlite (Node 22.5), with instant reset.

await sqlite.exec("INSERT INTO items (name) VALUES (?)", "widget");
const rows = await sqlite.query("SELECT name FROM items");
await sqlite.reset();

ContainerService

Generic Docker/Podman orchestration with healthchecks.

import { ContainerService } from "js-test";
const redis = new ContainerService({
    image: "redis:7-alpine",
    ports: { "6379": 0 },                       // 0 = dynamic host port
    healthCheck: { type: "tcp", port: 6379 }
});

Skipping when infrastructure is absent

Every service has probe():

const probe = await pg.probe();
if (!probe.available) return t.skip(probe.reason);

ServiceManager (without a server)

import { ServiceManager, SqliteService } from "js-test";
const services = new ServiceManager([new SqliteService()]);
const env = await services.start();   // { DATABASE_URL: "file:..." }
t.after(() => services.stop());

10. Testing a CLI

Run a companion CLI against the running server; the base URL and auth token are forwarded via env (BASE_URL, AUTH_TOKEN).

const suite = await createSuite(t, {
    binary: "./.cxy/build/my-server",
    cli: "./.cxy/build/my-cli",
    healthCheck: "/healthz"
});

const { code, stdout, stderr, output, timedOut } = await suite.cli(["project", "list"], { token });
suite.equals("cli exits cleanly", 0, code);
suite.has("cli lists a project", "acme/backend", { text: output });
  • token is forwarded as AUTH_TOKEN (or as --token <value> if you pass

tokenArg: "--token").

  • Timeouts return { timedOut: true } rather than hanging.

11. Mock external services

Mock HTTP server

const mock = await suite.mockHttp({
    "POST /oauth/token": { access_token: "mock-tok", token_type: "Bearer" },
    "POST /webhooks/incoming": (req) => ({ status: 200, body: { received: true, event: req.json.event } }),
    "GET /users/*": (req) => ({ status: 200, body: { path: req.path } })
});

// point your app at it
const suite2 = await createSuite(t, { /* ... */ env: { AUTH_PROVIDER_URL: mock.url } });

// later
mock.assertCalled("POST /webhooks/incoming", 1);
suite.equals("webhook event", "ping", mock.lastRequest.json.event);

Routes are keyed by "METHOD /path" (with * wildcards). Each recorded request has { method, path, query, headers, body, json, matched }.

Mock WebSocket server

const mock = await suite.mockWs();
mock.onConnection((conn) => conn.send("welcome"));

const ws = suite.ws("/socket");
await ws.open();
suite.equals("greeting", "welcome", await ws.next());

mock.assertReceived("hello", 1);

12. Browser testing

Chromium (headless, isolated) is the default; Safari is opt-in.

const browser = await suite.browser();          // chromium
const page = await browser.newPage();
await page.goto(`${suite.base}/items`);

// geometry
const box = await page.getBox(".item-card");
await page.checkBox("card is wide enough", box, (b) => b.width > 200);

// computed styles (resolved values, camelCased keys)
const style = await page.getStyle(".btn-primary");
await page.checkStyle("button is blue", ".btn-primary", (s) => s.backgroundColor === "rgb(0, 123, 255)");

// interaction
await page.click(".btn-details");
await page.waitForSelector(".item-modal");
await page.type("#name", "hello");
await page.press("Enter");                       // real keydown/keyup
await page.clickAt(10, 10);                       // click at coordinates (e.g. a backdrop)
await page.setViewport(375, 667);                 // responsive checks

// authenticate as a logged-in user (sets the HttpOnly session cookie)
await page.setCookie({ name: "session_token", value: token, url: suite.base, httpOnly: true });
  • page.screenshot() writes a .png named after the test + label.
  • page.check/checkBox/checkStyle screenshot on failure.
  • console.error / uncaught exceptions fail the test at teardown.
  • page.press(key) accepts named keys (Enter, Escape, Backspace, Tab,

arrows) or a single character (e.g. ",").

  • Safari: suite.browser({ engine: "safari" }) (needs a one-time

safaridriver --enable; it takes over your running Safari).


13. SSR / DOM validation (fast, no browser)

Validate server-rendered HTML in-memory (< 5 ms):

const res = await suite.get("/");
const report = suite.validateHtml(res.text, {
    sprite: spriteSvg,                       // served icons.svg
    sensitiveKeys: ["password", "secret"],   // props leak denylist
    requireCsrf: true,
    requireModuleScript: true
});
assert.deepEqual(report.violations, []);

Catches: nested <a>/<button>/<form>, interactive content inside <a>, missing icon sprite symbols, invalid/leaky JSON props blocks, and unauthorized CDN references. Each violation has { rule, message, tag, line, path }.


14. Run artifacts & reporters

Every run creates one directory: .cxy/build/tests/run-<timestamp>-<pid>/:

run-.../
  logs/                 # server stdout/stderr
  screenshots/          # failure screenshots (named after the test)
  failures/             # full failing HTTP responses
  results.json          # if you passed --reporter json
  <name>-memory-<pid>.txt  # Cxy memory report (see 16)
  manifest.json         # run id, timings, config, counts, artifacts

Old runs are pruned automatically, keeping the newest JS_TEST_KEEP_RUNS (default 5). Override the base with --artifacts-dir.

Reporters:

--stdout spec|tap|dot|json|junit|none   # stdout format (default spec)
--reporter tap --reporter json          # write results.tap + results.json
--stdout none --reporter json           # no stdout, only results.json

15. Project configuration (test.config.mjs)

Optional, at your repo root. Merged over defaults; CLI flags win.

// test.config.mjs
export default {
    binary: "./.cxy/build/my-server",
    cli: "./.cxy/build/my-cli",
    artifactsDir: "./.cxy/build/tests",
    keepRuns: 5,
    reporters: ["json"],
    loginPath: "/api/v1/auth/login",
    browser: { engine: "chromium", headless: true },
    memory: { failOn: "watch" }
};

16. Memory analysis (Cxy servers)

When your server is a Cxy binary built with memory tracing, js-test drives cxy utils mem automatically: it marks a baseline at boot and analyzes at close.

const report = await suite.memory();
// { verdict: "clean" | "finding" | "error" | "unavailable", exitCode, reportPath, details }
  • clean (exit 0) / finding (exit 3, details written to the run dir) /

error (dead server, no socket) / unavailable (no cxy).

  • Disable with --no-memory.

17. A complete example

// tests/api/items.test.mjs
import test from "node:test";
import { createSuite, PostgresService } from "js-test";

test("items API end-to-end", async (t) => {
    const db = new PostgresService({
        command: ["docker", "exec", "test-postgres", "psql"],
        user: "postgres",
        seed: ["CREATE TABLE items (id serial primary key, name text not null)"]
    });

    const suite = await createSuite(t, {
        binary: "./.cxy/build/my-server",
        args: (port) => ["--port", port, "--db-url", db.getConnectionUrl()],
        services: [db],
        healthCheck: "/healthz"
    });

    const token = await suite.login("admin", "secret");

    const created = await suite.post("/items", { name: "widget" }, suite.bearer(token));
    suite.check("create returns 201", 201, created);

    const list = await suite.get("/items", suite.bearer(token));
    suite.jcheck("list contains widget", (j) => j.items.some((i) => i.name === "widget"), list);

    // verify persistence directly
    suite.equals("row persisted", "1", await db.scalar("SELECT count(*) FROM items WHERE name = 'widget'"));

    // fast SSR check on the rendered page
    const page = await suite.get("/items");
    suite.equals("no DOM violations", [], suite.validateHtml(page.text).violations);
});

18. Migrating from the Python harness

If you're porting suites from a Python harness (e.g. crunch/tests/api/lib.py), the mapping is direct:

Python harness js-test
Suite(__file__) createSuite(t, { ... })
s.start_server("--enable-ui") createSuite(t, { args: ["--enable-ui"] })
s.call("POST", "/x", body, auth=tok) suite.post("/x", body, suite.bearer(tok))
s.check(name, want, res) suite.check(name, want, res)
s.equals(name, want, got) suite.equals(name, want, got)
s.has/hasnt/jcheck suite.has/hasnt/jcheck
Database (docker exec psql) PostgresService({ command: ["docker","exec","<c>","psql"] })
s.cli(token, ...) suite.cli([...], { token })
s.finish() automatic (via t.after)
cxy utils mem suite.memory() (automatic)

19. Tips & troubleshooting

  • -f still runs everything. Like the Python harness, -f only reports

matching checks; later tests may depend on earlier setup. Use -s to limit files.

  • Server didn't start? The error includes the last ~30 lines of the server's

output. Check <runDir>/logs/.

  • Browser tests skip? Chromium isn't found (install chrome-headless-shell

or set CHROME_PATH), or Safari is opt-in (--browser safari).

  • Service tests skip? The service's probe() reported unavailable (e.g.

Docker isn't running, or Postgres/Redis isn't reachable).

  • node:sqlite requires Node 22.5.
  • Everything is zero-npm if you find yourself wanting an npm package, check

whether a platform built-in or a cxy utils command already covers it.

Install
cxy package add js-test
Versions
0.1.32026-11-25T12:12:11Z
0.1.2yanked2026-11-25T12:09:13Z
0.1.1yanked2026-11-25T12:05:58Z