Testing plugins
Exercise standalone Worker handlers and persistent local storage, then make sure that platform staging integration works.
Separate local handler tests from real platform acceptance. A fixture is test data, not platform authorization. Local tests need no Novinzo source, private package, production credential, or token-signing secret.
| Layer | Public tooling | What it exercises |
|---|---|---|
| Pure logic | Node.js test runner or Vitest | Parsing, calculations, and state decisions |
| Local Worker | Wrangler local runtime and HTTP requests | Routing, D1, tenant isolation, and durable writes |
| Admin screen | Browser automation or DOM tests | MessagePort protocol and rendered states |
| Platform staging | Registered private Worker and Novinzo staging store | Dispatch, installation, grants, and signed invocations |
The Vitest configuration
Vitest is optional. The runnable suite below uses Node's built-in test runner against Wrangler's local Worker. It needs no additional test dependency. Use a dedicated local project or storage directory rather than a production database.
For pure JavaScript modules, Vitest also works independently:
npm install --save-dev vitest
npx vitest runYour tests import your own modules, not platform package exports. Use Cloudflare's public Workers testing tools when a suite needs direct Worker binding access or runtime-controlled fault injection. See Cloudflare Workers testing.
D1 migrations in tests
Use the quickstart project and its committed SQL migrations. Apply them locally before starting the test server:
npm run db:local
npm run devWrangler serves the example on http://localhost:8787.
Its local D1 database persists across requests and restarts.
The suite below uses fresh UUIDs instead of depending on automatic row cleanup.
Run storage-failure tests in a separate runtime with a failing D1 binding or unavailable database.
Make sure that failed webhook writes return 500, not 2xx.
Do not alter a live database to create a failure fixture.
The core-for-plugins stub
A local service fixture tests outbound HTTP behavior, not Novinzo authentication.
A fake invocation token never establishes plugin or tenant identity against live core.
Neither binding properties nor x-novinzo-plugin-name establish that identity.
When a handler calls the platform, record its binding requests and assert these properties:
- The request uses
env.CORE_FOR_PLUGINS.fetch, not public network fetch. - The placeholder origin is
https://core-for-plugins.internal. - The path and JSON body match the public HTTP contract.
- The inbound
x-novinzo-plugin-invocationvalue is forwarded unchanged. - A missing invocation fails before any platform request.
- Malformed responses and service failures never become successful authorization.
Return fixture responses only for explicitly exercised paths. Fail unexpected calls instead of returning generic success. Label every fixture result as local protocol evidence. Never store a real invocation token in snapshots or committed fixtures.
For POST /api/api-access-credentials/verify, the body is { "token": "<presented bearer credential>" }.
A successful response is 200 { "storeId": "<uuid>" }.
Rejected credentials return 401 { "_tag": "c4p/ApiAccessCredentialRejected" }.
Exercise a credential from another store and another plugin as rejection cases. Credential verification requires a valid current invocation and is scoped to that invocation's store. An outage, malformed success response, or unexpected error is not a rejected credential. Keep those error paths distinct and fail closed. See Calling the platform for complete HTTP usage.
Call the entry point with an HTTP client
This suite runs the complete quickstart Worker through local HTTP, including its actual D1 queries.
Save it as test/purchases.test.mjs.
The quickstart's npm test script runs it with Node's test runner.
import test from "node:test";
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
const base = "http://localhost:8787";
const fixtureToken = "local-fixture-only";
const headers = (storeId) => ({
"x-novinzo-plugin-invocation": fixtureToken,
...(storeId ? { "x-novinzo-store-id": storeId } : {}),
});
const purchase = () => ({
storeId: randomUUID(),
variantId: randomUUID(),
customerId: randomUUID(),
orderId: randomUUID(),
quantity: 2,
});
const post = (path, body) =>
fetch(base + path, {
method: "POST",
headers: { ...headers(), "content-type": "application/json" },
body: JSON.stringify(body),
});
const get = (path, storeId) => fetch(base + path, { headers: headers(storeId) });
const salesPath = (variantId) => `/storefront-public/variants/${variantId}/sales`;
await test("health reaches the local database", async () => {
const response = await fetch(base + "/health");
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { status: "ok" });
});
await test("concurrent purchase redelivery writes once", async () => {
const event = purchase();
const replies = await Promise.all(
Array.from({ length: 8 }, () => post("/webhooks/variant-purchased", event)),
);
for (const reply of replies) assert.equal(reply.status, 204);
const list = await get("/admin/purchases", event.storeId);
assert.equal(list.status, 200);
const rows = await list.json();
assert.equal(rows.length, 1);
assert.equal(rows[0].orderId, event.orderId);
assert.equal(rows[0].variantId, event.variantId);
assert.equal(rows[0].quantity, 2);
assert.equal("customerId" in rows[0], false);
const count = await get(salesPath(event.variantId), event.storeId);
assert.equal(count.status, 200);
assert.deepEqual(await count.json(), { sold: 2 });
});
await test("the same order and variant stay isolated between stores", async () => {
const a = purchase();
const b = { ...a, storeId: randomUUID(), quantity: 5 };
assert.equal((await post("/webhooks/variant-purchased", a)).status, 204);
assert.equal((await post("/webhooks/variant-purchased", b)).status, 204);
assert.deepEqual(await (await get(salesPath(a.variantId), a.storeId)).json(), { sold: 2 });
assert.deepEqual(await (await get(salesPath(b.variantId), b.storeId)).json(), { sold: 5 });
const unrelated = await get("/admin/purchases", randomUUID());
assert.deepEqual(await unrelated.json(), []);
});
await test("deletion is tenant-scoped and survives delayed redelivery", async () => {
const a = purchase();
const b = { ...a, storeId: randomUUID() };
for (const event of [a, b]) {
assert.equal((await post("/webhooks/variant-purchased", event)).status, 204);
}
const deletion = { storeId: a.storeId, variantId: a.variantId };
for (let attempt = 0; attempt < 2; attempt++) {
assert.equal((await post("/webhooks/variant-deleted", deletion)).status, 204);
}
assert.equal((await post("/webhooks/variant-purchased", a)).status, 204);
assert.deepEqual(await (await get(salesPath(a.variantId), a.storeId)).json(), { sold: 0 });
assert.deepEqual(await (await get("/admin/purchases", a.storeId)).json(), []);
assert.deepEqual(await (await get(salesPath(b.variantId), b.storeId)).json(), { sold: 2 });
});
await test("invalid requests do not create purchases", async () => {
const event = purchase();
assert.equal((await post("/webhooks/variant-purchased", { ...event, quantity: 0 })).status, 400);
assert.equal(
(await post("/webhooks/variant-purchased", { ...event, customerId: "invalid" })).status,
400,
);
const malformed = await fetch(base + "/webhooks/variant-purchased", {
method: "POST",
headers: { ...headers(), "content-type": "application/json" },
body: "{",
});
assert.equal(malformed.status, 400);
const missing = await fetch(base + "/admin/purchases", {
headers: { "x-novinzo-store-id": event.storeId },
});
assert.equal(missing.status, 401);
const noStore = await get("/admin/purchases");
assert.equal(noStore.status, 400);
assert.deepEqual(await noStore.json(), { _tag: "MissingStoreIdError", reason: "missing-header" });
const badStore = await get("/admin/purchases", "invalid");
assert.equal(badStore.status, 400);
assert.deepEqual(await badStore.json(), { _tag: "MissingStoreIdError", reason: "invalid-uuid" });
assert.deepEqual(await (await get("/admin/purchases", event.storeId)).json(), []);
});The tests deliberately supply a fake token without any platform secret. They prove handler behavior under local fixtures, not token signature enforcement, seller authorization, or live installation grants.
| Surface | Local fixture inputs |
|---|---|
| Admin and storefront | Store header plus fake invocation header |
| Webhooks | Store header plus fake invocation header |
| Functions | Store header plus fake invocation header, with matching payload tenant when present |
| Credential-protected route | Invocation fixture plus a separate bearer credential fixture |
For the function example, add fixtures for these paths:
- A stock shortfall returns only the requested variant with its requested and available quantities.
- An unknown stock row reports zero available rather than success.
- Key reads return only rows matching both store and order.
- Changed discount revisions return the tagged
400refusal body. - A mismatched header and payload store returns
403without accessing another tenant. - Database outages return
500, never an empty success response.
Isolation between tests
Give every test a fresh store UUID. Keep all seed data and read predicates scoped to that store. Use identical order and variant identifiers in two tenants to detect missing store predicates.
The HTTP suite uses Wrangler's persistent local database. It does not depend on a testing pool's storage-isolation defaults. Restart the Worker between manual exercises to make sure that deduplication survives isolate replacement.
Testing the admin screen
Use your own browser or DOM tests against the public admin-screen protocol. A local dashboard fixture implements the documented MessagePort exchange, not a private bridge package.
Exercise these behaviors:
- The screen announces readiness and renders the supplied store context.
- Admin requests contain the intended method, path, headers, and body.
- Responses match request identifiers and preserve failure statuses.
- Destructive actions wait for the documented confirmation response.
- Changing the store context clears stale tenant data.
- A disconnected port or failed request displays an error without exposing secrets.
Local DOM tests do not prove iframe origin boundaries or Novinzo's seller permission enforcement. Exercise those boundaries in a real staging dashboard.
Running the tests
Keep npm run dev running, then execute this command in another terminal:
npm testA stopped local Worker causes a connection failure. Start Wrangler instead of replacing requests with fake success responses. Use your chosen formatter, linter, and type checker through their public CLI commands. No private build system is required.
Platform test helpers
External plugin tests never need Novinzo token-signing helpers or secrets. Local fixtures test forwarding and failure behavior only. Real token authentication belongs to staging integration with Novinzo-issued requests.
Do not treat a locally constructed token, decoded JWT body, or binding property as authorization evidence. Do not replay a captured token after the original invocation ends. No cron or detached background task receives store access without a current valid platform invocation.
Smoke tests
Coordinate a staging installation and deployment with Novinzo.
There is no public self-service provisioning endpoint.
Novinzo provides dispatch registration, subscription configuration, service bindings, and the staging installation.
The deployed Worker keeps workers_dev=false and preview_urls=false.
Run acceptance through real Novinzo surfaces:
- Complete a staging checkout and observe one durable purchase per order and variant.
- Read admin purchases through the dashboard as an authorized seller.
- Read public sales through the staging store's storefront proxy.
- Repeat reads from another store and make sure that no tenant data crosses the boundary.
- Exercise a retry after a transient failure and make sure that no duplicate purchase appears.
- Remove the installation and make sure that platform calls stop succeeding.
- Exercise expired invocation and rejected credential cases with Novinzo's staging support.
- Exercise live function failure behavior, including hidden keys and fail-closed checkout stock.
- Exercise migration retries with repeated review keys when review import is supported.
Separate local fixture results from staging evidence in the release record. Record the request surface, tenant, expected status, and observed result without recording tokens or customer credentials. See Deployment for coordinated production rollout.
