Skip to content

Test without an account

Terminal window
npx @sparkletree/cli dev # mock edge on http://127.0.0.1:4330
npx @sparkletree/cli dev --failure offline # every request fails
import { startMockEdge, mockEmbedApi, mockFetch } from "@sparkletree/core/testing";

@sparkletree/core/testing is a mock of the SparkleTree edge for tests and local development. It answers the same endpoints as the real edge, with the same shapes and statuses: the islands stream, islands/copy, content, fragments and their mint, track, whoami, facts, the signing keys document and /ask. The streams replay the recorded fixtures the real edge is tested against, bundled in the package. You need no account, no keys and no network.

Never deploy it. It answers CORS for any origin and accepts unsigned keys.

Out of the box it serves one workspace, one campaign and one surface, with these ids (MOCK_IDS):

Id
organizationId 00000000-0000-4000-8000-000000000001
campaignId 00000000-0000-4000-8000-000000000002
surfaceId 00000000-0000-4000-8000-000000000003
variantId 00000000-0000-4000-8000-000000000004

The campaign has the products stoneware-mug (249.00 SEK, in stock) and linen-cloth (out of stock), and its variant the custom slots eyebrow, note and promoLine: the names the examples in these pages use, so they show a value landing when run against the mock.

Any other campaign or surface id is unknown, as it would be on the real edge, so a test for a wrong id means something. Add your own campaigns, content and fragments with the scenarios option.

Terminal window
npx @sparkletree/cli dev
Mock edge running at http://127.0.0.1:4330
Point your project at it, for example in .env.development.local:
NEXT_PUBLIC_SPARKLETREE_KEY=st_pk_test_eyJ…
NEXT_PUBLIC_SPARKLETREE_API_BASE=http://127.0.0.1:4330
NEXT_PUBLIC_SPARKLETREE_ORG_ID=00000000-0000-4000-8000-000000000001
NEXT_PUBLIC_SPARKLETREE_CAMPAIGN_ID=00000000-0000-4000-8000-000000000002
Press Ctrl+C to stop.

Put those lines in your development env file and restart your dev server. The names follow your framework (--framework, or read from package.json), as with init. The values depend only on the port, so the same lines work every time. --port <n> picks another port; --failure <name> makes every request act out one failure. Each event the mock receives is logged on stderr. Ctrl+C stops it.

mockFetch() is a fetch answered in process, with no server and no ports. Pass it to the provider as fetchImpl. It carries a test key and the mock’s ids, so the provider needs nothing else.

// hero.test.tsx (Vitest, environment "jsdom", with @testing-library/react)
import { cleanup, render, waitFor } from "@testing-library/react";
import { afterEach, expect, it } from "vitest";
import { Hero, SparkletreeProvider } from "@sparkletree/react";
import { mockFetch, type MockFetch } from "@sparkletree/core/testing";
const fallback = { headline: "Handmade stoneware", body: "Fired in small batches." };
function renderHero(fetchImpl: MockFetch) {
const { container } = render(
<SparkletreeProvider publishableKey={fetchImpl.publishableKey} fetchImpl={fetchImpl}>
<Hero campaignId={fetchImpl.campaignId} fallback={fallback} />
</SparkletreeProvider>,
);
return container.querySelector(".st-hero")!;
}
// Testing Library unmounts after each test by itself only under `globals: true`.
afterEach(cleanup);
it("plays the streamed copy and counts the impression", async () => {
const fetchImpl = mockFetch({ pace: 0 });
const hero = renderHero(fetchImpl);
await waitFor(() => expect(hero.getAttribute("data-phase")).toBe("settled"));
expect(hero.textContent).toContain("This headline streamed from the mock edge");
// The impression is sent after the copy settles: wait for it to arrive.
await waitFor(() => expect(fetchImpl.events().map((event) => event.eventType)).toContain("impression"));
fetchImpl.close();
});
it("keeps the fallback when the edge is down", async () => {
const fetchImpl = mockFetch({ failure: "offline" });
const hero = renderHero(fetchImpl);
await waitFor(() => expect(hero.getAttribute("data-phase")).toBe("failed"));
expect(hero.textContent).toContain(fallback.headline);
expect(hero.querySelector('[data-content-source="generated"]')).toBeNull();
fetchImpl.close();
});

afterEach(cleanup) unmounts what a test rendered. Testing Library does this by itself only when Vitest runs with globals: true; without it the first test’s Hero stays mounted and decides what the second one shows. pace: 0 sends every stream frame at once, so the test does not wait for copy to be paced the way a generation lands. Relative URLs resolve against apiBase (default http://127.0.0.1:4330); absolute URLs are answered whatever their host. close() stops every delay and open stream.

startMockEdge() runs the mock as an HTTP server on 127.0.0.1. Node only. Start it on a fixed port and give the app under test the env lines sparkletree dev prints for that port.

e2e/hero.spec.ts
import { expect, test } from "@playwright/test";
import {
expectNoLayoutShift,
installLayoutShiftObserver,
layoutShift,
startMockEdge,
type MockEdge,
} from "@sparkletree/core/testing";
let edge: MockEdge;
test.beforeAll(async () => {
edge = await startMockEdge({ port: 4330 });
});
test.afterAll(async () => {
await edge.close();
});
test.beforeEach(() => {
edge.reset();
edge.setFailure(null);
});
test("copy lands without moving the page", async ({ page }) => {
await installLayoutShiftObserver(page);
await page.goto("/");
await expectNoLayoutShift(page);
expect((await layoutShift(page)).total).toBe(0);
expect(edge.events().some((event) => event.eventType === "impression")).toBe(true);
});
test("a slow edge: the fallback lands and nothing moves", async ({ page }) => {
edge.setFailure("slow");
await installLayoutShiftObserver(page);
await page.goto("/");
await expectNoLayoutShift(page);
await expect(page.locator(".st-hero")).toContainText("Handmade stoneware");
});

startMockEdge resolves to the server’s url and port, a publishableKey whose API base is that server, the mock’s ids (organizationId, campaignId, surfaceId, variantId), events(), reset(), setFailure() and close(). Without port it takes any free port. host sets the interface.

The Vite plugin serves the mock from the dev server (and vite preview) at the page’s own origin. Paths the mock does not serve go on to Vite.

vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { mockEmbedApi } from "@sparkletree/core/testing";
export default defineConfig({
plugins: [react(), mockEmbedApi()],
});
<SparkletreeProvider
apiBase={window.location.origin}
organizationId="00000000-0000-4000-8000-000000000001"
>

The plugin runs in Vite’s Node process and adds nothing to your build. It logs each event it receives to the console. plugin.handler is the shared handler, for reading events or setting a failure from your own dev setup. The runnable examples are built this way.

Failure What the mock does
offline Drops the connection.
slow Holds back the first byte for slowMs (default 3000 ms, longer than the SDK’s hold).
stall Sends part of the response and then nothing.
error-mid-stream Breaks the response part way. On the islands stream it ends with an error event, one chunk step after the last chunk (none at pace: 0).
http-500 Answers 500.
quota Serves the stored copy as static, with degraded: "quota".
unauthorized Answers 401 with an embed auth reason (unauthorizedReason, default origin_not_allowed) where the edge checks a key, and whoami answers ok: false with the same reason and its remedy. Fragment reads are not checked, on the real edge either, so they still serve. islands/copy checks no origin, so it refuses only for a key reason or org_mismatch.
over-long Sends copy far longer than the slot’s length budget.
empty Sends no copy.

Pick one in any of these ways. A choice for one request wins over a choice for the whole mock.

For How
The whole mock The failure option, setFailure(name) (null clears it), or sparkletree dev --failure <name>.
One request The query parameter ?st-mock=<name> or the header x-st-mock: <name>. An unknown name answers 400 with the list.
One campaign or surface The id st-mock-<name>, made by failureCampaignId(name). Every request that names it fails that way.

fixtureCampaignId(name) (st-fixture-<name>) replays one recorded fixture exactly as recorded; FIXTURES lists them.

When the integration is right, every failure ends with readable copy and no layout shift. Check this with expectNoLayoutShift for each one.

Failure On the page
offline, http-500, unauthorized data-phase="failed". Your fallback, readable, with no adapted provenance (data-content-source is static).
slow The block holds, its space reserved by your invisible fallback, then your fallback lands with one short fade when the hold runs out. The late stream is not shown: the fallback is final for the page view.
stall The same as slow: the stream opened, so the hold restarts once (at most 5 seconds in all), then your fallback lands and nothing replaces it. The mock types no text before it goes quiet. A real stream that types part of a line and then goes quiet has that line replaced once by your fallback 5 seconds after its last text.
error-mid-stream data-phase="failed". React (Hero, Cta, useIsland): the mock sends the error one chunk step after the half headline, so at the default pace the page shows the half line first. That half line is then replaced once by your fallback, with one cross-fade in the space it reserved, and the headline reads data-content-source="static". When the error arrives before the half line was painted, nothing is replaced, the headline reads data-content-source="static", and rewrites stays 0. There are two such cases. If the line started in an earlier network read and the chunk and the error came together in a later one, your fallback is typed into the slot that was still blank, at the typing pace (two characters a frame, about 300 ms for a 36-character headline; no motion under reduced motion). If the whole stream came in one read, as it does from the mock over HTTP at pace: 0, the headline was still held, so your fallback appears at once with no typing. A field that was still held (out of view) or that it never started gets your fallback, and a fallback already on screen stays. The custom elements (<sparkletree-island>) show no typing, so only a field the stream finished lands; the field it was writing and any it never started keep your served text.
quota data-phase="settled" and data-degraded="quota" on Hero. Real copy, the stored version, marked static, so nothing claims adapted provenance.
over-long Your fallback. Copy that does not fit the space your fallback reserved is not shown, so the slot neither grows nor moves the page.
empty data-phase="settled" with your fallback in every field.

The reason is the same each time: the fallback sets the slot’s size, and visible text is never replaced, except a line the stream did not finish, which ends on your fallback once. See When things go wrong and the layout doctrine.

Every event the mock’s /track received, oldest first:

edge.events(); // startMockEdge
fetchImpl.events(); // mockFetch
plugin.handler.events(); // mockEmbedApi

Over HTTP, from any of them: GET /__sparkletree/events answers { "events": [...] }, ?type=impression filters by event type, and DELETE /__sparkletree/events clears the list. reset() forgets the events and the minted fragments.

Member
receivedAt When the mock received it, ISO 8601.
eventType impression, click, conversion or custom (the page view is a custom event).
organizationId, campaignId, variantId When the event named them.
eventData What the SDK sent with it, such as context.island.
body The request body as sent.

They take a Playwright page (anything with addInitScript and evaluate) and import nothing from Playwright. Layout shifts are reported by Chromium only; elsewhere expectNoLayoutShift throws and says so.

Helper What it does
installLayoutShiftObserver(page) Records layout shifts from the start of every document the page loads. Call it before page.goto().
layoutShift(page) The shift recorded so far on this document: total, totalExcludingInput, entries (each with value, startTime, hadRecentInput and the nodes it moved), scrollHeight, supported, documentId.
waitForSettled(page, selector?, options?) Waits until the copy in selector (default: the whole page) has settled: nothing still reserved, holding or live, and something there stamped as settled. Then waits two frames, so late shift entries are in. Throws a readable error naming what is still pending.
expectNoLayoutShift(page, action?, options?) Runs action, waits for the copy to settle, and throws when anything moved: a layout shift, a change of document.documentElement.scrollHeight, or a change of a landmark element’s box. The error names each shift and each element that moved. Resolves to { shift, entries, scrollHeight, landmarks }.

The action must not navigate: navigate first, then check what follows. Without an action, expectNoLayoutShift checks from the moment it is called until the copy settles; layoutShift(page).total covers the whole load.

Option Default
selector the whole page Wait for the copy in this selector to settle.
timeoutMs 10 000 How long to wait for the settle.
tolerance 0 The total shift allowed.
ignoreInputShifts false Leave out shifts the browser flagged as following input, as web-vitals CLS does. Chromium flags shifts for about 500 ms after a click, so by default they count.
landmarks DEFAULT_LANDMARKS, the direct children of body and of main CSS selectors for the elements whose boxes must not change. [] skips the comparison. They catch a page shorter than the viewport, where content can move without the scroll height changing.
newSettle true After an action, wait for a new settle. Pass false when the action changes no SparkleTree copy.

waitForSettled takes timeoutMs, after (an action to run first, after which the settle must be a new one) and newSettle.

startMockEdge, mockEmbedApi and mockFetch share these options.

Option Default
scenarios the defaults Extra or replacement streams, content and fragments, merged over the defaults id by id.
failure none A failure for every request.
slowMs 3000 How long slow holds back the first byte.
pace 1 Multiplies every delay between stream frames. 0 sends every frame at once.
enforcement "log" The key and site check: log serves every request and stamps x-st-auth with the reason a key failed; required answers 401; off checks nothing.
origins any loopback origin Origins registered for live keys.
strictKeys false Check key signatures the way the real edge does. Needs keySecret; sign keys with signPublishableKey.
keySecret none The secret strictKeys checks against. A test value, never a real secret.
unauthorizedReason origin_not_allowed The reason the unauthorized failure reports, on whoami too.
organization The workspace /facts describes.
signFacts true Sign /facts with a throwaway key.
mintText the field’s fallback The text a fragment mint writes.
answer a fixed sentence The answer /ask gives.
livePlayback none A real Cloudflare Stream player, <label>.cloudflarestream.com/<uid>, for the recorded live card.
log false (true for the Vite plugin) true logs to the console; a function receives each line.

startMockEdge also takes port and host; mockFetch takes apiBase.

  • It accepts unsigned keys. Every well-formed publishable key is valid to it, including the keys it hands out. The real edge answers unsigned or bad_signature. With strictKeys: true and a test keySecret it checks signatures as the edge does; startMockEdge then signs the key it hands out, and mockFetch().publishableKey stays unsigned.
  • It accepts any workspace id. Fragment reads take any non-empty workspace, and facts and /ask take one that is not a UUID. The real edge answers 404 for a workspace it does not know.
  • It accepts its own ids where the edge wants a UUID: scenario ids, st-mock-… and st-fixture-…, on facts and /ask.
  • Live keys pass from loopback origins (http://localhost:*, http://127.0.0.1:*) unless you set origins. There are no platform or brand-domain origin rules.
  • It answers CORS for any origin. The real edge answers a browser only on registered sites, verified brand domains and localhost.
  • It writes new fragment copy from localhost. The hosted edge does not: it refuses a mint from a loopback origin whatever the key, so on localhost against the hosted edge a fragments group shows copy already written and its fallbacks otherwise. The mock is the way to see fragment copy land while you develop.
  • Copy does not depend on context. Time of day, device, language and declared context change nothing: each id always serves its scenario’s copy, and islands/copy always answers it as fresh.
  • There are no rate limits, except the quota failure.
  • unauthorized on islands/copy refuses only when unauthorizedReason is a key reason or org_mismatch, the reasons that route’s key check can give; with an origin reason, the default, it serves.
  • /ask writes a fixed answer (or the one answer returns), needs no proof of the workspace, and sends no follow-up questions.
  • Facts are signed with a throwaway key made when the mock starts, and legal lines are not narrowed to the viewer’s market.
  • Track does not check that the variant belongs to the campaign, and has no per-session event budget.

Before you ship, check the real setup with sparkletree doctor.