JavaScript testing
Use calmlens/testing to test your JavaScript SDK integration offline, with mock clients, storage, API keys and webhook deliveries. Keep these imports in test files: the main, /server and /app entry points exclude testing utilities from production bundles.
Setup
import { MockCalmLensServerClient, createMockApiKey } from "calmlens/testing";
const client = new MockCalmLensServerClient({
apiKey: createMockApiKey(),
projectId: "proj_8fK2mQx7Lp4NvB3tRz9Y",
});createMockApiKey() mints mock keys locally without contacting CalmLens. projectId is optional on the mock and defaults to project-1.
MockCalmLensServerClient is a CalmLensServerClient, so your code receives the real client. Every method runs the real client's code: options are checked, requests are built and responses and errors are read exactly as against CalmLens. Instead of the network, its requests go to an in-memory CalmLens API and CDN that answer them as CalmLens does, with the same HTTP statuses, response bodies, error bodies and headers. Nothing leaves the process. MockCalmLensAppClient does the same for the app client.
App client
MockCalmLensAppClient takes the app client's options plus mockOptions.server, the MockCalmLensServerClient whose project receives the uploads, and mockOptions.preset, the upload preset rules the in-memory API applies (requireToken, allowedContentTypes, maxFileSizeInBytes, visibility, folderId and so on). Read the uploads back through server:
import { MockCalmLensAppClient } from "calmlens/testing";
const app = new MockCalmLensAppClient({
uploadPresetId: "preset_4Lk8Qw2Xm9Rt5Vb3Nc7P",
mockOptions: {
server: client,
preset: { allowedContentTypes: ["image/*"], maxFileSizeInBytes: 5_000_000 },
},
});
const upload = await app.assets.create({
name: "avatar.png",
content: { base64: pngBase64, type: "image/png" },
});
const stored = await app.server.assets.retrieve({ assetId: upload.id });Without mockOptions.server, the app client creates its own server mock, available as app.server. The preset also takes showDecisions and keepContentAfterProcessing, and the app client can check and continue only the uploads it made, with the API's error codes. To run the upload widget on it, pass createClient: (options) => new MockCalmLensAppClient({ ...options, mockOptions }).
Outcomes and options
Configure moderation, deterministic IDs and clocks, and storage with mockOptions:
let nextId = 0;
const client = new MockCalmLensServerClient({
apiKey: createMockApiKey(),
projectId: "proj_8fK2mQx7Lp4NvB3tRz9Y",
mockOptions: {
// Generate deterministic, unique IDs for snapshot testing
createId: (prefix) => `${prefix}_${String(++nextId).padStart(20, "0")}`,
// Fix timestamps for reproducible assertions
now: () => 1_700_000_000_000,
// Decides each upload (see "Moderation decisions" below)
moderate: ({ content }) => (content.text?.includes("spam") ? "blocked" : "allowed"),
},
});Moderation decisions
mockOptions.moderate decides each asset the mock moderates. It receives:
asset: the stored asset, still processing.content: the uploadedbytes, andtextfor a plain-text upload such astext.classify. Both arenullwhen there is no content, such as for a website.trigger: why the asset is moderated:upload,retry(afterassets.retry),rerun(afterassets.explainwithrerun: true) orcomplete(see below).queued:truewhen CalmLens would queue the work rather than answer with the decision: queued uploads, retries, reruns andcomplete.
It returns a status, pending, failed, allowed, limited, age-restricted, blocked or purged, or a decision built with mockDecision, and may return a promise of either. A failed asset gets classification.failureReason processing-error. Without moderate, queued uploads, retries and reruns stay pending and everything else is allowed.
mockDecision(status) builds a decision with findings: flag(category, score, qualifiers?) records a category's score from 0 to 1 and, optionally, its qualifiers' scores, and notEvaluated(category) marks a category as not assessed. A decided asset gets a complete report, as from CalmLens: raw.categories holds every category (unflagged ones evaluated with score 0), categories holds each evaluated category's policy score and action, and flaggedCategories lists the categories the decision acted on (categories scored 0.5 or more, unless the status is allowed). An unknown category or qualifier, or a score outside 0 to 1, throws sdk/invalid-argument.
import { MockCalmLensServerClient, createMockApiKey, mockDecision } from "calmlens/testing";
const client = new MockCalmLensServerClient({
apiKey: createMockApiKey(),
projectId: "proj_8fK2mQx7Lp4NvB3tRz9Y",
mockOptions: {
moderate: ({ content }) =>
content.text?.includes("kill")
? mockDecision("blocked").flag("violence", 0.92, { "violence-threat": 0.9 })
: "allowed",
},
});
const comment = await client.text.classify({ text: "I will kill you" });
const violence = comment.classification.moderation.raw?.categories.violence;
expect(violence).toMatchObject({ status: "evaluated", score: 0.92 });
expect(comment.classification.moderation.flaggedCategories).toEqual(["violence"]);A moderate function decides queued uploads straight away too. Return pending for them (queued && trigger === "upload") to finish them later.
Finish processing
client.completeProcessing(assetId, decision?) finishes processing a pending asset as CalmLens would, with the decision you pass or else the one moderate returns for the complete trigger (allowed by default). It records no review, so the asset can still be moderated again with assets.explain. It fails with 404 asset/not-found for an unknown asset and sdk/invalid-argument for an asset that isn't processing or awaiting a pending re-run:
const upload = await client.assets.create({
name: "photo.png",
content: { base64: pngBase64, type: "image/png" },
}); // pending
await client.completeProcessing(upload.id, mockDecision("age-restricted").flag("sexual", 0.8));
const decided = await client.assets.waitForDecision({ assetId: upload.id });
expect(decided.classification.moderation.status).toBe("age-restricted");The mock accepts the same options as CalmLensServerClient (baseUrl, cdnBaseUrl, timeoutMs, maxRetries and so on) and rejects invalid ones the same way. Requests never leave the process, whatever fetch you pass. cdn.getAssetUrl and cdn.signAssetUrl use cdnBaseUrl, which defaults to mock://calmlens/v1.
Keys from createMockApiKey() have no grants. Pass grants to create a key that has them, such as createMockApiKey([{ actions: ["assets:download"], folderId: null, includeSubfolders: true }]), and change them later with client.setApiKeyGrants(grants).
Storage
client.databaseStorage and client.imageStorage hold the mock's records and uploaded bytes. Use them in assertions to verify saved records without extra API calls:
// Inspect database records directly
const asset = await client.databaseStorage.getAsset(createdAsset.id);
const allAssets = await client.databaseStorage.listAssets(projectId);
const folder = await client.databaseStorage.getFolder(createdFolder.id);
const allFolders = await client.databaseStorage.listFolders(projectId);
// Inspect raw binary upload content and multipart parts
const storedContent = await client.imageStorage.getContent(createdAsset.id);
console.log(storedContent?.type); // "image/png"
console.log(storedContent?.parts.get(1)); // Uint8Array of bytesTo track method calls or simulate storage failures, pass your own implementations of MockDatabaseStorage or MockImageStorage. Extending the in-memory stores lets you override one method:
import {
MockCalmLensServerClient,
InMemoryMockDatabaseStorage,
InMemoryMockImageStorage,
createMockApiKey,
} from "calmlens/testing";
class FailingDatabaseStorage extends InMemoryMockDatabaseStorage {
override async getAsset(): Promise<undefined> {
throw new Error("Database unavailable");
}
}
const databaseStorage = new FailingDatabaseStorage();
const imageStorage = new InMemoryMockImageStorage();
const client = new MockCalmLensServerClient({
apiKey: createMockApiKey(),
projectId: "proj_8fK2mQx7Lp4NvB3tRz9Y",
mockOptions: { databaseStorage, imageStorage },
});What the mock simulates
The in-memory API reproduces CalmLens where tests usually depend on it. It doesn't classify content: decisions come from your moderate option.
- Errors carry the API's
code, HTTPstatus,details, arequestIdand responseheaders, soerror.isNotFound()and status checks work as they do against CalmLens. Options the real client refuses before sending, such as a missing asset name, fail the same way without a request. assets.listappliessortandfilter, includingfolderId==, like the API: the documented asset fields with==,!=,>,>=,<,<=,=in=and=out=, joined by;(and), which binds tighter than,(or), and grouped with parentheses, as in(name==a.png,name==b.png);type==image.*in an==or!=value matches any run of characters, ignoring case. Any other field or operator, such as=like=or=gt=, fails with 400 filter/invalid, and asortwith an unknown or repeated field, or more than two fields, fails with 400 validation/invalid-request (issuevalidation/invalid-valueat pathsort). Its cursors resume after the last asset returned, so assets created or deleted between pages are neither repeated nor skipped.assets.iteratepages through the results.folders.list,hashLists.list,hashLists.listEntries,policies.listandlenses.listreturn cursor pages like the API, each with its iterator: folders by name unlesssortsays otherwise, hash lists, entries and lenses newest first, policies oldest first.- The project starts on the organisation's own General policy,
liveon preset release 1. The mock's presets define every category with its default action, allow for personal information and profanity and block otherwise, and no rules; uploads are decided bymoderate, never by a policy. Settings that leave out a category, or a category'saction,allowancesorrestrictions, fail with 400 validation/invalid-request whose issue names the first missing path, such assettings.categorySettings.hate. lenses.createwith an identifier the project already uses fails with 409 lens/identifier-taken, and an unknown lens ID with 404 lens/not-found.assets.searchruns the API's keyword search: every word of the query must appear, in any case, in the asset's name, ID, external ID, description, tags, type, content format or extension, or moderation status. Results have the API's keyword scores andmatchedFields, best match first, then newest first. There is no semantic search, sosemanticStatusisdisabled.- Assets created one after another get increasing
createdAtvalues, so sorting bycreatedAtis predictable. PassmockOptions.nowto control the clock. - A second asset with the same
externalIdfails with 409 asset/duplicate-external-id. - New objects get IDs like the API's: the kind's prefix, an underscore and 20 random base62 characters, such as
asset_5Gm2Rk8XqT3wLp9VbN4c.mockOptions.createIdreceives the prefix (asset,fldr,hl,hle,lens,evtorrev). - Unset asset fields are
null, as the API returns them. Out-of-rangepageSizevalues and search queries fail with 400 validation/invalid-request, whose issue isvalidation/too-smallorvalidation/too-big. - Multipart parts must arrive in order (409 upload-part/invalid-number with
details.expectedPartNumber), every part but the last is at least 5 MiB, images total 10 MiB to 20 MiB, and parts add up to any declaredtotalSizeInBytes. Thewaitchoice made at the start applies to the final part unlessassets.uploadPartoverrides it, and parts after it fail with 409 upload/not-open. - Content is removed with reason retention once processing finishes unless
keepContentAfterProcessingis set; an automated purged outcome removes it with reason policy, andassets.removeContentand a reviewer's purge with reason requested. - Reusing an
idempotencyKeyreturns the first response; reusing it for a different request fails with 409 idempotency/key-reused, and a request that failed frees its key. assets.waitForDecisiontakes no real time: it returns a completed or failed asset, and fails withsdk/timeoutstraight away for one that stays queued or processing.- Every upload adds asset.uploaded to the events feed, then asset.classified and the automated
asset.<status>(whoseactoris automated) once it is decided, or asset.failed.assets.retry,assets.removeContentandassets.deleteadd asset.retried, asset.content-removed and asset.deleted.assets.explainwithrerun: trueadds asset.rerun-requested and returns the asset unchanged: it keeps its decision until the onemoderatereturns replaces it, and keeps it when that isfailed. A pending re-run waits forcompleteProcessing.
CDN serving and access control
cdn.serve and cdn.getAssetInfo requests are answered by the in-memory CDN, which serves the stored bytes and each asset's info, names assets by ID or ext: external ID, and checks access control like CalmLens. client.fetchCdn(url, init?) fetches one of its URLs as a browser would, without the API key, such as a signed asset URL with a resource appended. Like the CDN, it returns Content-Type, Content-Length and X-Request-Id headers, an ETag for images, and Cache-Control as the CDN sets it (public only when anyone may see the asset, otherwise private; max-age=31536000, immutable for images and max-age=3600 for other content; private, no-store when the request carries viewerClaims), or a JSON error body:
- Blocked, purged and failed assets, and assets whose content was removed, return
403with 403 asset/not-available, whatever the key. - Private assets return
403with 403 auth/permission-denied unless the key has assets:download for the asset's folder. - Signed asset URLs work until they expire, then return
403with 403 signed-url/expired;/originalunder a grant without original access returns403with 403 signed-url/original-not-granted. - Age-restricted assets require
viewerClaims.ageConfirmed: true, including requests using signed URLs or API keys; otherwise delivery returns403with 403 viewer/age-confirmation-required. - Unknown assets return
404with 404 asset/not-found. - A classified image's
placeholderresource is a PNG, public for every asset whatever its visibility or status, and refused once the asset is purged or its content removed.
Responses also carry Cache-Tag and the CDN's protection headers, and images an Expires header.
// Public assets can be served directly
const publicAsset = await client.assets.create({
name: "public.png",
content: { base64: pngBase64, type: "image/png" },
visibility: "public",
});
const response = await client.cdn.serve({ assetId: publicAsset.id });
expect(response.status).toBe(200);
// A key without assets:download cannot read private assets directly
const privateAsset = await client.assets.create({
name: "secret.png",
content: { base64: pngBase64, type: "image/png" },
visibility: "private",
});
const privateResponse = await client.cdn.serve({ assetId: privateAsset.id });
expect(privateResponse.status).toBe(403);
// A signed asset URL serves it to a browser without the key
const { url } = await client.cdn.signAssetUrl({ assetId: privateAsset.id });
const signedResponse = await client.fetchCdn(`${url}/rendered`);
expect(signedResponse.status).toBe(200);Events and reviewer decisions
Besides the events the mock records itself, add events with client.enqueueEvent, which resolves to the stored event. An event about a stored asset carries the asset as it is, as from CalmLens. An asset.<status> event carries the moderation status it announces, as CalmLens sends it once the asset has that status. Read them with a cursor as you would from the API:
const { nextCursor: cursor } = await client.events.list(); // a cursor for "now"
await client.enqueueEvent({ type: "asset.allowed", assetId: asset.id });
const page = await client.events.list({ cursor });
expect(page.items.map((event) => event.type)).toEqual(["asset.allowed"]);client.decide(assetId, decision) applies a reviewer's decision (allowed, limited, age-restricted, blocked or purged) to a stored asset: its moderation status changes, purged also removes the content, and an asset.<decision> event whose actor is a user joins the feed:
await client.decide(asset.id, "blocked");
const { items } = await client.events.list({ cursor });
expect(items.at(-1)).toMatchObject({ type: "asset.blocked", assetId: asset.id });client.decide is a test hook for a reviewer's decision: it applies any decision, records the review without a note and adds the event; pending and failed are not decisions and throw sdk/invalid-argument. To finish processing as CalmLens's moderation would, use completeProcessing. assets.decide, the client method your code calls, is checked like the API: it fails with 409 asset/decision-not-allowed when an asset pending moderation is allowed, limited or age-restricted, 409 asset/decision-unchanged when the status would not change, 409 asset/content-purged when purged content is anything but blocked, and 409 asset/processing while an upload is still open or processing, such as a queued upload still pending. It records the note with the reviewer name An API key.
Recorded requests and failures
Every request the client sends is recorded in client.calls, oldest first, as { operation, method, url, path, query, headers, body, status }:
operationis the client method that sends the request, such as"assets.retrieve","events.list"or"cdn.serve". A request that several methods send is recorded under the underlying one: atext.classifyupload as"assets.classify", awaitForDecisionpoll as"assets.retrieve".pathis relative to the API or CDN base URL, so it leaves out/v1, with each segment decoded, such as/assets/<id>.queryholds the query parameters as sent.bodyis the parsed JSON body, the text of a text upload or the bytes of a file upload.statusis the HTTP status the in-memory API answered with, orundefinedfor a request that failed without a response.
client.callsTo(operation) returns the requests one method sent. A request that several methods send matches each of them: text.classify sends an assets.classify upload, assets.waitForDecision polls with assets.retrieve, ensureLens sends ensureLenses, and the iterators send list requests. Methods that send nothing are not recorded, such as uploadTokens.sign, which signs locally, or an ensureLens answered from the client's lens cache:
await client.text.classify({ text: "hello", externalId: "comment-1" });
expect(client.callsTo("text.classify")).toEqual([
expect.objectContaining({
method: "POST",
query: expect.objectContaining({ externalId: "comment-1", wait: "true" }),
body: "hello",
status: 200,
}),
]);client.clearCalls() forgets the requests recorded so far.
client.failNextRequest() makes the next request fail as if the network had failed, so the client throws the CalmLensError that CalmLensServerClient throws when a request cannot complete (code: "sdk/transport-error", with the network error as cause). It also takes:
| Argument | Failure |
|---|---|
"timeout" | sdk/timeout |
An API error code, such as "usage/free-uploads-exhausted" | That error and its HTTP status |
A CalmLensError | Thrown as is |
Another Error | sdk/transport-error, with it as the cause |
{ operation } limits the failure to the next request that method sends. For an API error, details sets the error's details and retryAfter answers with a Retry-After of that many seconds, so you can test code that reads error.details or error.retryAfter; they don't apply to transport errors or timeouts, and an operation the client doesn't have throws sdk/invalid-argument. Each queued failure fails one request, so a retry takes the next queued failure or reaches the in-memory API:
client.failNextRequest("timeout", { operation: "text.classify" });
await expect(client.text.classify({ text: "hello" })).rejects.toMatchObject({
code: "sdk/timeout",
});
await expect(client.text.classify({ text: "hello" })).resolves.toMatchObject({
classification: { moderation: { status: "allowed" } },
});client.failNextRequest("upload/website-rate-limit-reached", { retryAfter: 30 });
await expect(client.assets.list()).rejects.toMatchObject({ status: 429, retryAfter: 30 });The mock's maxRetries defaults to 0, unlike the real client, so a failed request fails once; set it to test how your code handles retries. Retry backoff takes no real time.
Webhook handlers
toWebhookEventPayload turns an event into a delivery body, and createWebhookHeaders signs it the way CalmLens does, so your handler's parseWebhookEvent or verifyWebhookSignature call runs unchanged:
import { createWebhookHeaders, toWebhookEventPayload } from "calmlens/testing";
const event = await client.enqueueEvent({ type: "asset.allowed", assetId: asset.id });
const body = JSON.stringify(toWebhookEventPayload(event));
const headers = await createWebhookHeaders({ secret, body, deliveryId: "dlv_3Vm8Qk2Xt7Lp9Rb4Nw6C" });
const response = await handler(new Request("http://localhost/webhooks", { method: "POST", body, headers }));createWebhookHeaders uses the current time unless you pass timestampSeconds. To build only the x-calmlens-signature value, call createWebhookSignatureHeader(secret, timestamp, body).
Upload tokens
signUploadToken(apiKey, options, { now, nonce }) from calmlens/testing signs an upload token like uploadTokens.sign at a fixed time (epoch milliseconds) and nonce, checking options the same way, so tests can compare exact tokens. The mock's own uploadTokens.sign signs at mockOptions.now with a random nonce.
Media test codes
generateMediaTestCode(signal, testInputKey) builds audio and video test codes from your project's secret test input key.
Generate test inputs
Use these helpers to generate authenticated text and PNG inputs for a project with Recognise test inputs turned on in its settings (it is off by default). They come from calmlens/test-inputs and need your project's test input key. Presets use the same editable instance format as the test input builder.
CalmLens recognises a text code only when it is the whole text you submit (surrounding whitespace aside), and a test image only when it is the whole upload. A code inside other text, or a test image drawn into a larger picture, is moderated as ordinary content.
import { generateTestTextCode, paintTestImage, TEST_INPUT_PRESETS, type TestInput } from "calmlens/test-inputs";
const input: TestInput = structuredClone(TEST_INPUT_PRESETS.mixed);
input.instances = input.instances.map((instance) => ({ ...instance, action: "limit" }));
input.instances.push({ category: "harassment", qualifiers: ["harassment-abuse"], action: "block" });
const text = await generateTestTextCode(input, testInputKey);
const { width, height, rgba } = await paintTestImage(input, testInputKey);
// Encode these RGBA pixels as a lossless PNG using the returned dimensions.detectTestTrigger(text, testInputKey) and detectTestImage({ width, height, rgba }, testInputKey) read a code or image back, the way CalmLens recognises one. They return the scenario, or undefined for anything CalmLens would moderate as ordinary content.
Set action on every instance to choose its outcome independently of the project policy. Actions are allow, limit, age-restrict and block; the strongest wins. The image and text code carry identical outcomes. Omit every instance action when testing the normal policy resolver instead. Do not mix the two forms.
For delivery testing without category evidence, set explicit regional actions:
const regionalInput: TestInput = {
instances: [],
regionalActions: [
{ region: "DE", action: "block" },
{ region: "GB", action: "age-restrict" },
{ region: "FR", action: "limit" },
],
};
const regionalText = await generateTestTextCode(regionalInput, testInputKey);
const regionalImage = await paintTestImage(regionalInput, testInputKey);Every project serves these jurisdictions; an EU outcome needs the project to opt into the EU. These restrictions apply to the matching viewer region and cannot soften a stricter base decision or jurisdiction rule. See regional outcome testing for CDN requests and expected results. The regionalDelivery preset supplies this same example.