Testing

Testing

Journeys are code, so they are tested like code. Type errors, compile checks, an accelerated clock for local runs, and the whole engine in-process over PGlite in a vitest test.

A journey that takes ten days to play out is hard to test in a tool where it only exists on a canvas. In Sendwend it is a TypeScript module, and the engine that runs it is an ordinary library. That gives four layers of checks, each cheaper than the next one up: the type checker, the compiler, an accelerated clock for running the real host locally, and the full engine running in-process inside a unit test, where ten days pass in milliseconds. This page goes through each, with a complete test you can copy.

Type errors come first

The contract types every reference, so most mistakes never reach a test. Each of these fails in the editor:

ts
.email(email.welcome, { nmae: u.name })        // not a prop of the template
.email(email.welcome, {})                      // required prop 'name' is missing
.email(push.welcome_push, { name: u.name })    // a push template where an email is expected
.delay('3 dyas')                               // not a duration
.branch([eq(u.platform, 'ios '), ...])         // not one of the enum's values
trigger.event(e.purchase, (p) => gt(p.vlaue, 100)) // not a field of the payload
workflow({ id: 'welcome', trigger })           // `reentry` is required
emailTemplate({ id: 'tip', topic: 'tipz', ... }) // a topic the contract does not declare

Types flow from the contract's Zod schemas, so a renamed event field shows up as an error in every workflow that reads it. Run tsc --noEmit in CI and this layer costs nothing.

What the compiler catches

Some things cannot be types: whether a template is registered, whether two templates share an id, whether a segment a workflow uses is in the config. compileConfig(config) checks them, in a few milliseconds and without a database, and throws ConfigCompileError naming the workflow and the node:

MistakeMessage
A template the workflow sends is not in templatesworkflow 'welcome' node 0: email template 'nudge' is not registered
A required prop is missingworkflow 'welcome' node 0: email 'nudge': required prop 'name' is missing
A prop reads a profile field the contract does not declareworkflow 'welcome' node 0: email 'nudge': 'name' reads u.nickname, which the contract's profile does not declare

It also refuses an id registered twice in a channel, a different template definition registered under the id a workflow sends, a literal prop the schema refuses, a topic the contract does not declare, a trigger payload field the event does not declare, an emitted event that does not match the contract, a segment or action that is used but not listed, and a payload condition outside a where. Those last ones come from compileBundle, which compileConfig runs first.

A test that compiles the config catches all of it, and the compiled IR is plain JSON, so it is snapshot-testable: a snapshot diff shows exactly which nodes a change moved.

ts
import { compileConfig } from 'sendwend';
import { expect, test } from 'vitest';
import config from '../workflow.config';

test('the journeys compile', () => {
  expect(compileConfig(config)).toMatchSnapshot();
});

An accelerated clock

To watch a journey on a real host, in wrangler dev or a staging deploy, run it in fast-forward. The config holds runtime options per mode, and the host's ENVIRONMENT variable picks the entry (production when unset). A mode with no entry runs in real time:

ts
// workflow.config.ts
export default defineConfig({
  // ...
  runtime: { development: { timeScale: 600, logMessages: true } },
});

timeScale divides every duration in a journey by the factor. At 600, delay('1 day') sleeps 2.4 minutes, so the welcome journey's delay('3 days') followed by a waitUntil with a 7-day timeout plays out in 24 minutes. At 3600, '2 days' is 48 seconds. The pinned content hash is unchanged: the journey runs the same version, faster.

logMessages: true logs every outbound message as it is handed to the sender, with its channel, template, recipient and resolved props:

text
[journey] email getting_started → ada@example.com {"name":"Ada"}

What is scaled and what is not

Everything that is a duration scales together, so a journey keeps its shape:

  • delays and random delays;
  • waitUntil timeouts;
  • the goal's within window;
  • performed(..., { within }) windows, in the workflow, in the segments it reads, and in a trigger's profile filter.

Some things are not durations and are not scaled:

  • Time windows are skipped. A timeWindow is a time of day, which cannot be compressed. A scaled journey drops it instead of sleeping real hours until 09:00.
  • The re-entry cooldown is not among the scaled fields.
  • A trigger.date time is a calendar time, and the sweep that starts it runs on the host's cron.

production is held to real time by its type (ProductionRuntimeOptions): a development factor pasted under the production key is a compile error, not every user's journey compressed. A deploy that is meant to run fast is not production; give it a mode of its own (ENVIRONMENT=rehearsal), which is as free as development.

The whole engine in a unit test

The Node host, journeyNode from sendwend/node, needs nothing but a Postgres client. Over PGlite, Postgres compiled to WebAssembly and run in-process, the entire engine runs inside a vitest test: the HTTP API, ingest, routing, the entry ledger, the runner, segment membership, the delivery claim. Two methods drive it with nothing started in the background:

  • journeys.fetch(request) is the host's HTTP API as a fetch handler: deploy the bundle, ingest events, change subscriptions.
  • journeys.drain() takes every run that is due now a turn further, and returns what each turn came to.

Fake Date and a ten-day journey takes milliseconds. Pass messages and every copy lands in an array instead of a provider. This is how the SDK tests its own Node host.

The test below drives the welcome journey from the quick start, end to end:

ts
// src/workflows/welcome.ts
export const welcome = workflow({
  id: 'welcome',
  reentry: { mode: 'never' },
  trigger: trigger.event(e.sign_up),
})
  .email(email.getting_started, { name: u.name })
  .delay('3 days')
  .waitUntil(performed(e.activated), {
    timeout: '7 days',
    onTimeout: (w) => w.email(email.nudge, { name: u.name }),
  });

Install the test dependencies:

bash
pnpm add -D vitest @electric-sql/pglite
ts
// tests/welcome.test.ts
import { PGlite } from '@electric-sql/pglite';
import type { OutboundMessage } from 'sendwend/engine';
import { journeyNode } from 'sendwend/node';
import { type SqlClientLike, renderPostgresDdl } from 'sendwend/store';
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
import config from '../workflow.config';

const DAY = 24 * 60 * 60 * 1000;

/** The engine's `SqlClientLike` over PGlite: Postgres in-process, nothing to start. */
function pgliteClient(
  db: Pick<PGlite, 'query'> & Partial<Pick<PGlite, 'transaction'>>
): SqlClientLike {
  return {
    query: async (text, params = []) =>
      (await db.query(text, [...params])).rows as never,
    transaction: (fn) =>
      db.transaction === undefined
        ? fn(pgliteClient(db))
        : db.transaction((tx) =>
            fn(pgliteClient({ query: tx.query.bind(tx) }))
          ),
  };
}

let pg: PGlite;
let sent: OutboundMessage[];
let journeys: ReturnType<typeof journeyNode>;

beforeEach(async () => {
  vi.useFakeTimers({
    now: Date.parse('2026-12-01T09:00:00Z'),
    toFake: ['Date'],
  });
  pg = await PGlite.create();
  await pg.exec(renderPostgresDdl()); // the engine's tables, in the `workflow` schema
  sent = [];
  journeys = journeyNode({
    config,
    sql: pgliteClient(pg),
    vars: { ENVIRONMENT: 'test' }, // a mode that runs without API_TOKEN
    // Every copy lands here instead of a provider
    messages: () => ({ send: async (message) => void sent.push(message) }),
  });
  await post('/bundle/deploy');
});

afterEach(async () => {
  vi.useRealTimers();
  await pg.close();
});

async function post(path: string, body?: unknown) {
  const response = await journeys.fetch(
    new Request(`http://journeys${path}`, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: body === undefined ? undefined : JSON.stringify(body),
    })
  );
  expect(response.status).toBe(200);
}

/** Move the clock forward, running every turn that comes due on the way. */
async function advance(ms: number) {
  const target = Date.now() + ms;
  await journeys.drain();
  for (
    let next = await journeys.runtime.nextWake();
    next !== undefined && next <= target;
  ) {
    vi.setSystemTime(Math.max(next, Date.now()));
    await journeys.drain();
    const after = await journeys.runtime.nextWake();
    if (after === next) break;
    next = after;
  }
  vi.setSystemTime(target);
  await journeys.drain();
}

const signUp = () =>
  post('/ingest', {
    userId: 'u_1',
    profile: { email: 'ada@example.com', name: 'Ada' },
    events: [{ event: 'sign_up', id: 'signup-u_1' }],
  });

test('a user who never activates gets the welcome, then the nudge ten days later', async () => {
  await signUp();
  await journeys.drain();
  expect(sent.map((m) => m.template)).toEqual(['getting_started']);
  expect(sent[0]).toMatchObject({
    recipient: 'ada@example.com',
    props: { name: 'Ada' },
  });

  await advance(3 * DAY + 7 * DAY);
  expect(sent.map((m) => m.template)).toEqual(['getting_started', 'nudge']);
});

test('a user who activates during the wait gets no nudge', async () => {
  await signUp();
  await advance(4 * DAY);
  await post('/ingest', {
    userId: 'u_1',
    events: [{ event: 'activated', id: 'act-u_1' }],
  });
  await advance(30 * DAY);
  expect(sent.map((m) => m.template)).toEqual(['getting_started']);
});

test('a redelivered sign-up enters once', async () => {
  await signUp();
  await signUp();
  await journeys.drain();
  expect(sent).toHaveLength(1);
});

What is going on:

  • renderPostgresDdl() returns the engine's tables as plain DDL, the same tables your migrations create in production. A fresh PGlite takes a second or two to start; for a large suite, create one in beforeAll and empty the tables between tests.
  • /bundle/deploy compiles the config the host was built with and writes the routing table, exactly as a production deploy does, including the in-flight and schema checks.
  • /ingest is the request your api makes through JourneyClient. It is validated against the contract, so a payload your api could not send fails here too.
  • drain() runs the turns that are due. After the sign-up, the run sends the welcome email, reaches the delay, and suspends until three days later.
  • advance() moves the faked clock from one wake to the next (journeys.runtime.nextWake() says when the next run is due), draining as it goes. A wait that nobody answers comes due at its timeout and takes the onTimeout branch; an activated event wakes the run early.
  • messages replaces the host's channels with your own MessageSender. Each copy is an OutboundMessage with the channel, template id, resolved props, recipient, topic and idempotency key. Leave it out to test the real senders against a fake transport.

The same harness reaches everything the HTTP API does: PUT /subscriptions/:userId to test that an unsubscribed user skips a topic email, POST /devices to test a push, POST /segments/sweep (or journeys.sweep()) to test a segment entered by the clock. Custom actions run for real, so an action that records its calls is a probe of its own.

For the engine alone, without a host or a database, runJourney from sendwend/engine runs one journey against ports you implement in memory, with registryRenderer (sendwend/react-email) and registryPushRenderer (sendwend/push) rendering what it sends.

How the SDK tests itself

The same approach, at scale, is how the package is tested. The interpreter is tested through its ports, never against a platform. The Node host is tested over PGlite with a faked clock, the way the example above does it. And the conformance suite runs one config on Node, Cloudflare and AWS, drives each through the HTTP API every host serves, and holds them to the same observable results: the actions called, the copies handed to the sender, and the entry, instance, message, event and subscription tables. A scenario never names a host, so what you test on the Node host locally is what the other hosts are held to. See Architecture.

When an AI agent writes the journey

These layers matter most when the author is a coding agent. A journey written through a UI can only be checked by a person clicking through it. A journey written as code can be checked by the agent that wrote it, without anyone in the loop:

  1. Type-check. A misspelled event field, a missing prop or a missing reentry is a compiler error with a line number, which the agent reads and fixes.
  2. Compile. compileConfig names the workflow and node for every registry and contract mistake, in words.
  3. Run the journey. A test like the one above plays ten days in under a second, and its assertions state what the journey should do: who gets which message, in which order, and who does not.
  4. Read the result. A failing assertion, a ConfigCompileError or a logged message says what went wrong precisely enough to act on.

So most mistakes are caught and fixed before a person looks. What is left for review is the part only a person can judge: whether this is the journey you want to send.

  • Versioning: plan() and the in-flight check, which belong in CI next to these tests.
  • Self-hosting: the same journeyNode in production.
  • Steps: what each step does when the test drives it.