Testing with fakes
@safran/kit/testing holds everything needed to test code that uses Safran, and connectors written for it, without a network, a tracker account or an embedding model. This page shows a complete bun:test file for code that takes a Safran instance, a complete connector test with mockFetch, and what each fake does.
The fakes are real implementations of the contracts, backed by memory. A FakeTracker is a Tracker; an instance built over it runs the same routing, capability checks, paging and cancellation code it runs in production. Only the far end is replaced.
| Export | What it is |
|---|---|
FakeTracker | An in-memory Tracker with tickets, comments, links, attachments, history and search. |
FakeCodeHost | An in-memory CodeHost with repositories and merged pull requests. |
FakeDocSource | An in-memory DocSource that claims one origin and serves pages by URL. |
FakeCodeIndex | An in-memory CodeIndex: searches, greps and reads the files you give it. |
FakeEmbedder | A deterministic, offline Embedder. |
fakeTrackerPlugin, fakeCodeHostPlugin, fakeDocSourcePlugin, fakeEmbedderPlugin, fakePlugins | Plugins of type fake that hand those connectors to createSafran. |
mockFetch | A fetch that answers from a route table and records every request. |
Test code that uses a Safran instance
The code under test collects what a person needs to start on a ticket. It takes the instance as an argument, which is all the "dependency injection" a test needs:
import type { CallOptions, Safran } from "@safran/core";
export interface Triage {
key: string;
title: string;
/** Teams that own the ticket's project, by declaration. */
owners: string[];
/** The query that was searched, after glossary expansion. */
searchedFor: string;
/** Distinct `repo/path` of the best code hits. */
files: string[];
/** URLs the ticket links to that a doc source can fetch. */
docs: string[];
}
/** Collects what a person needs to start on a ticket: who owns it, where the code is, what to read. */
export async function triage(safran: Safran, ref: string, options: CallOptions = {}): Promise<Triage> {
const ticket = await safran.tickets.get(ref, options);
const { teams } = await safran.company.whoOwns({ project: ticket.project }, options);
const search = await safran.code.search(ticket.title, { limit: 5, ...options });
// Links are optional: a tracker without them still gets a triage.
const { tracker } = safran.tickets.resolve(ref);
const links = tracker.capabilities.has("links") ? await safran.tickets.links(ref, options) : [];
return {
key: ticket.key,
title: ticket.title,
owners: teams.map((team) => team.name),
searchedFor: search.effectiveQuery,
files: [...new Set(search.hits.map((hit) => `${hit.repo}/${hit.path}`))],
docs: links.flatMap((link) => (link.kind === "web" && link.url !== undefined && safran.docs.canFetch(link.url) ? [link.url] : [])),
};
}A fixture builds the acme story in memory. It returns the fakes next to the instance, so tests can change them and assert on what they were asked:
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createSafran, defineProfile, type Safran, type TrackerCapability } from "@safran/core";
import { FakeCodeHost, FakeCodeIndex, FakeDocSource, FakeTracker, fakePlugins } from "@safran/kit/testing";
export const WIKI_PAGE = "https://acme.atlassian.net/wiki/spaces/PAY/pages/4711/Refund-runbook";
export interface Acme {
safran: Safran;
jira: FakeTracker;
azure: FakeCodeHost;
wiki: FakeDocSource;
index: FakeCodeIndex;
}
/** The acme story in memory. Every test gets its own instance and its own data directory. */
export async function createAcme(options: { trackerCapabilities?: TrackerCapability[] } = {}): Promise<Acme> {
const jira = new FakeTracker({
id: "jira",
baseUrl: "https://acme.atlassian.net",
...(options.trackerCapabilities === undefined ? {} : { capabilities: options.trackerCapabilities }),
tickets: [
{
key: "PAY-1423",
title: "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor",
type: "Bug",
status: "Done",
statusCategory: "done",
comments: [{ id: "c1", body: "Yuvarlama hatası görünüyor." }],
links: [
{ kind: "ticket", relation: "blocks", ticket: { key: "PAY-1500", title: "Refund webhook retries are not idempotent" } },
{ kind: "web", relation: "mentioned in", url: WIKI_PAGE, title: "Refund runbook" },
{ kind: "web", relation: "mentioned in", url: "https://intranet.acme.test/handbook" },
],
},
{ key: "PAY-1500", title: "Refund webhook retries are not idempotent", statusCategory: "in_progress" },
{ key: "PAY-1501", title: "Checkout basket total ignores the campaign discount", statusCategory: "todo" },
],
});
const azure = new FakeCodeHost({
id: "azure",
repos: [{ name: "payments-api" }, { name: "ledger" }],
pullRequests: [
{ id: "101", repo: "payments-api", title: "PAY-1423 fix partial refund rounding", description: "", mergedAt: "2026-10-20T09:00:00Z", linkedTicketKeys: [], changedFiles: ["src/refund/service.ts", "src/refund/policy.ts"] },
],
});
const wiki = new FakeDocSource({
id: "wiki",
origin: "https://acme.atlassian.net",
pages: { [WIKI_PAGE]: { title: "Refund runbook", content: "# Refund runbook\n\nPartial refunds are rounded to two decimals." } },
});
const index = new FakeCodeIndex({
groups: { backend: ["payments-api", "ledger"] },
files: {
"payments-api": {
"src/refund/service.ts": "export class RefundService {\n createPartialRefund() {}\n}\n",
"src/refund/policy.ts": "export class RefundPolicy {\n roundRefundAmount() {}\n}\n",
"src/webhook/retry.ts": "export function handleRefundWebhook() {}\n",
},
ledger: { "src/entry.ts": "export function chargebackEntry() {}\n" },
},
});
const safran = await createSafran({
profile: defineProfile({
version: 1,
company: "acme",
languages: { tickets: "tr", code: "en" },
trackers: [{ id: "jira", type: "fake", projects: ["PAY", "MOB", "WEB"] }],
code: { hosts: [{ id: "azure", type: "fake" }], groups: { backend: ["payments-api", "ledger"] } },
docs: [{ id: "wiki", type: "fake" }],
teams: [{ name: "Payments", projects: ["PAY"], repos: ["payments-api", "ledger"] }],
glossary: [{ term: "İade", code: ["refund", "chargeback"] }],
}),
dataDir: mkdtempSync(join(tmpdir(), "acme-test-")),
builtinPlugins: false,
plugins: fakePlugins({ trackers: [jira], hosts: [azure], docs: [wiki] }),
index,
});
return { safran, jira, azure, wiki, index };
}Three choices in it are worth copying:
builtinPlugins: falsewithfakePlugins(...): the registry holds only the fakes, so a typo in the fixture cannot reach a real service.indexis aFakeCodeIndex: no SQLite file, no embedder.- A fresh
dataDirper instance: the links store is a real SQLite file, and tests must not share one.
The tests:
import { describe, expect, test } from "bun:test";
import { isSafranError } from "@safran/core";
import { createAcme, WIKI_PAGE } from "./acme";
import { triage } from "./triage";
describe("triage", () => {
test("collects owners, code and fetchable docs for a ticket", async () => {
const acme = await createAcme();
await using safran = acme.safran;
const result = await triage(safran, "pay-1423");
expect(result.key).toBe("PAY-1423");
expect(result.owners).toEqual(["Payments"]);
// The glossary turned "iade" into the words the code uses.
expect(result.searchedFor).toBe("Kısmi iade işlemi İstanbul şubesinde başarısız oluyor refund chargeback");
expect(result.files).toContain("payments-api/src/refund/service.ts");
// Only the link a configured doc source recognises; the intranet URL is left out.
expect(result.docs).toEqual([WIKI_PAGE]);
});
test("asks the index once, with the expanded query and the limit", async () => {
const acme = await createAcme();
await using safran = acme.safran;
await triage(safran, "PAY-1423");
expect(acme.index.count("search")).toBe(1);
const [query, options] = acme.index.last("search");
expect(query).toContain("refund chargeback");
expect(options).toMatchObject({ limit: 5 });
// The tracker was reached with the canonical key, whatever was typed.
expect(acme.jira.calls.filter((call) => call.method === "getTicket").map((call) => call.args[0])).toEqual(["PAY-1423"]);
});
test("a tracker without links still gets a triage", async () => {
const acme = await createAcme({ trackerCapabilities: ["comments", "search"] });
await using safran = acme.safran;
const result = await triage(safran, "PAY-1423");
expect(result.docs).toEqual([]);
expect(acme.jira.calls.some((call) => call.method === "getLinks")).toBe(false);
});
test("an unknown ticket is NOT_FOUND, not an empty triage", async () => {
const acme = await createAcme();
await using safran = acme.safran;
const failure = await triage(safran, "PAY-9999").catch((error: unknown) => error);
expect(isSafranError(failure, "NOT_FOUND")).toBe(true);
// Nothing was searched for a ticket that does not exist.
expect(acme.index.count("search")).toBe(0);
});
test("a failing index surfaces its error", async () => {
const acme = await createAcme();
await using safran = acme.safran;
acme.index.failure = new Error("disk full");
await expect(triage(safran, "PAY-1423")).rejects.toThrow("disk full");
});
test("cancellation stops a search that hangs", async () => {
const acme = await createAcme();
await using safran = acme.safran;
acme.index.hang = true;
const failure = await triage(safran, "PAY-1423", { signal: AbortSignal.timeout(50) }).catch((error: unknown) => error);
expect(isSafranError(failure, "ABORTED")).toBe(true);
});
test("the rest of the instance works on the same fakes", async () => {
const acme = await createAcme();
await using safran = acme.safran;
const page = await safran.docs.fetch(WIKI_PAGE);
expect(page.title).toBe("Refund runbook");
const report = await safran.links.refresh({ since: "2026-01-01" });
expect(report.repos.map((row) => [row.repo, row.status, row.linked])).toEqual([
["payments-api", "ok", 1],
["ledger", "ok", 0],
]);
expect((await safran.links.query({ ticket: "PAY-1423" })).flatMap((record) => record.changedFiles)).toEqual(["src/refund/service.ts", "src/refund/policy.ts"]);
const grep = await safran.code.grep("Refund", { groups: ["backend"], pathGlob: "*.ts" });
expect(grep.total).toBe(5);
});
});Test a connector with mockFetch
A connector is tested one level down: build it the way Safran does, give it a fetch that answers from a table, and assert on what it returns and what it sent. The connector here is the doc source from the plugins page, repeated so that this page is complete:
import { asRecord, asString, createHttpClient, defineDocSource, envVarName, httpUrl, isoDate, SafranError, type DocPage, type HttpClient } from "@safran/kit";
import { z } from "zod";
const configSchema = z.strictObject({
id: z.string().min(1),
type: z.literal("acme-handbook"),
url: httpUrl,
token_env: envVarName,
});
export const acmeHandbook = defineDocSource({
type: "acme-handbook",
description: "Pages of the Acme Handbook",
configSchema,
create(config, ctx) {
const origin = new URL(config.url).origin;
let client: HttpClient | undefined;
const http = (): HttpClient =>
(client ??= createHttpClient({
service: "Acme Handbook",
baseUrl: `${origin}/api`,
headers: { authorization: `Bearer ${ctx.secret(config.token_env)}` },
fetch: ctx.fetch,
logger: ctx.logger,
notFoundHint: "Check the link in the ticket; the page may have been moved or deleted.",
}));
/** `/p/<slug>` on our own origin, or undefined. Parsed, never prefix-matched. */
const slugOf = (url: string): string | undefined => {
try {
const parsed = new URL(url);
if (parsed.origin !== origin) return undefined;
return /^\/p\/([a-z0-9-]+)\/?$/.exec(parsed.pathname)?.[1];
} catch {
return undefined;
}
};
return {
id: config.id,
type: "acme-handbook",
matchUrl: (url) => slugOf(url) !== undefined,
async getPage(url, options): Promise<DocPage> {
const slug = slugOf(url);
// Safran only calls getPage after matchUrl; a connector still never fetches what it does not own.
if (slug === undefined) throw new SafranError("INVALID_INPUT", "Not an Acme Handbook page URL");
const body = await http().json({ path: `pages/${slug}`, ...(options?.signal ? { signal: options.signal } : {}) });
const page = asRecord(body);
const updatedAt = isoDate(page?.updated_at);
return {
source: config.id,
url,
title: asString(page?.title) ?? slug,
content: asString(page?.markdown) ?? "",
...(updatedAt === undefined ? {} : { updatedAt }),
};
},
};
},
});import { describe, expect, test } from "bun:test";
import { isSafranError, parsePluginConfig, silentLogger, type DocSource, type PluginContext } from "@safran/kit";
import { mockFetch, type MockRoute } from "@safran/kit/testing";
import { acmeHandbook } from "./handbook";
const PAGE_URL = "https://handbook.acme.test/p/refund-policy";
const API_URL = "https://handbook.acme.test/api/pages/refund-policy";
/** Builds the connector the way Safran does: validated config, then `create` with a context. */
async function connect(routes: MockRoute[], env: Record<string, string> = { HANDBOOK_TOKEN: "test-token" }) {
const mock = mockFetch(routes);
const context: PluginContext = {
company: "acme",
logger: silentLogger,
fetch: mock.fetch,
dataDir: "/work/acme/data/cache/handbook",
secret(name) {
const value = env[name];
if (value === undefined) throw new Error(`test setup: ${name} is not set`);
return value;
},
optionalSecret: (name) => (name === undefined ? undefined : env[name]),
};
const config = parsePluginConfig(acmeHandbook, { id: "handbook", type: "acme-handbook", url: "https://handbook.acme.test", token_env: "HANDBOOK_TOKEN" }, "docs.0");
const source: DocSource = await acmeHandbook.create(config, context);
return { source, requests: mock.requests };
}
describe("acme-handbook", () => {
test("claims only its own page URLs", async () => {
const { source, requests } = await connect([]);
expect(source.matchUrl(PAGE_URL)).toBe(true);
expect(source.matchUrl("https://handbook.acme.test/admin")).toBe(false);
expect(source.matchUrl("https://handbook.acme.test.attacker.test/p/refund-policy")).toBe(false);
expect(source.matchUrl("not a url")).toBe(false);
// Matching is offline.
expect(requests).toHaveLength(0);
});
test("happy path: fetches a page and maps it", async () => {
const { source, requests } = await connect([
{ method: "GET", url: API_URL, reply: { json: { title: "Refund policy", markdown: "Refunds are rounded to two decimals.", updated_at: "2026-10-01T12:00:00+0300" } } },
]);
const page = await source.getPage(PAGE_URL);
expect(page).toEqual({
source: "handbook",
url: PAGE_URL,
title: "Refund policy",
content: "Refunds are rounded to two decimals.",
updatedAt: "2026-10-01T09:00:00.000Z",
});
// The token travels in the header, to the right origin, and nowhere else.
expect(requests).toHaveLength(1);
expect(requests[0]?.headers.get("authorization")).toBe("Bearer test-token");
expect(requests[0]?.url.href).toBe(API_URL);
});
test("401 becomes AUTH_FAILED, without the token in the error", async () => {
const { source } = await connect([{ url: API_URL, reply: { status: 401, json: { error: "invalid token" } } }]);
const failure = await source.getPage(PAGE_URL).catch((error: unknown) => error);
expect(isSafranError(failure, "AUTH_FAILED")).toBe(true);
expect(JSON.stringify(failure)).not.toContain("test-token");
});
test("404 becomes NOT_FOUND with the connector's hint", async () => {
const { source } = await connect([{ url: API_URL, reply: { status: 404, text: "no such page" } }]);
const failure = await source.getPage(PAGE_URL).catch((error: unknown) => error);
expect(isSafranError(failure, "NOT_FOUND") && failure.hint).toBe("Check the link in the ticket; the page may have been moved or deleted.");
});
test("429 then success: the request is retried", async () => {
const { source, requests } = await connect([
{
url: API_URL,
// A list is consumed one reply per call; the last one repeats.
reply: [{ status: 429, headers: { "retry-after": "0" } }, { json: { title: "Refund policy", markdown: "Refunds are rounded." } }],
},
]);
const page = await source.getPage(PAGE_URL);
expect(page.title).toBe("Refund policy");
expect(requests).toHaveLength(2);
});
test("a request without a route fails loudly", async () => {
const { source } = await connect([]);
const failure = await source.getPage(PAGE_URL).catch((error: unknown) => error);
expect(isSafranError(failure, "INTERNAL") && failure.message).toBe(`mockFetch: no route for GET ${API_URL}`);
});
test("a cancelled call is ABORTED and makes no request", async () => {
const { source, requests } = await connect([{ url: API_URL, reply: { json: {} } }]);
const failure = await source.getPage(PAGE_URL, { signal: AbortSignal.abort() }).catch((error: unknown) => error);
expect(isSafranError(failure, "ABORTED")).toBe(true);
expect(requests).toHaveLength(0);
});
});Run both files:
$ bun test triage.test.ts handbook.test.ts
bun test v1.3.2 (b131639c)
14 pass
0 fail
36 expect() calls
Ran 14 tests across 2 files. [130.00ms]Where the test files must live is the same question as for any script that imports Safran: inside a package that declares @safran/core and @safran/kit as dependencies. See installation.
mockFetch
mockFetch(routes) returns { fetch, requests }. Pass fetch wherever a fetch is accepted: as createSafran({ fetch }), which hands it to every connector, or in a PluginContext as above.
| Route field | Meaning |
|---|---|
method | Optional. When set, only requests with this method match. |
url | A string is compared with the request's origin and path, without the query: it matches when equal, or when the request ends with it (so "/api/pages/refund-policy" is enough). A RegExp is tested against origin, path and query. |
reply | One reply; a list consumed one per call, the last one repeating; or a function of the recorded request. |
A reply is a Response, or an object with any of status (default 200), json, text, bytes and headers. The first route that matches answers, so put specific routes before general ones.
| Recorded field | Meaning |
|---|---|
method | The HTTP method. |
url | A parsed URL: assert on pathname and searchParams. |
headers | The request headers, to check that a token was sent (and where). |
body | The request body as text, or undefined. |
redirect | The redirect mode the caller passed to fetch, when it passed one. |
Three behaviours make tests reliable:
- A request without a route fails loudly. It throws a
SafranErrorwith codeINTERNALand the method and URL in the message. A test can never reach the network by accident, and a typo in a route shows up at once instead of after seconds of retry backoff. - Every request is recorded, also one that fails, so "no request was made" is an assertion you can write.
- Retries are real. The HTTP client's backoff runs as in production. Reply to a retried request with
retry-after: 0, as the 429 test does, so the test does not wait.
export interface MockRoute {
method?: string;
/** Matched against `origin + pathname` (string: exact or suffix match). */
url: string | RegExp;
/** A single reply, or a list consumed one per call (the last one repeats). */
reply: MockReply | MockReply[] | ((request: RecordedRequest) => MockReply | Promise<MockReply>);
}
export type MockReply = Response | { status?: number; json?: unknown; text?: string; headers?: Record<string, string>; bytes?: Uint8Array };
export interface RecordedRequest {
method: string;
url: URL;
headers: Headers;
body: string | undefined;
/** Redirect policy the caller passed to `fetch`, when it passed one. */
redirect?: "follow" | "manual" | "error";
}
export interface MockFetch {
fetch: typeof fetch;
requests: RecordedRequest[];
}defined in packages/kit/src/testing.ts
The fakes in detail
FakeTracker
| Option | Default | Meaning |
|---|---|---|
id | "fake" | The connector's id. Must equal the profile entry's id when used through fakePlugins. |
type | "fake" | Reported as tracker.type. |
projects | derived from the ticket keys | The projects matchTicketRef accepts and listProjects returns. |
tickets | none | FakeTickets: key and title are required, any Ticket field is allowed, plus comments, attachments, links and history. |
capabilities | all six | Narrow it to test what your code does with a limited tracker. |
baseUrl | https://tracker.test | Ticket URLs are <baseUrl>/browse/<KEY>, and matchTicketRef accepts that form. |
It recognises KEY-123 in any case for its known projects, and its own browse URLs. addTicket(ticket) adds one later. calls records every method call as { method, args }. Search matches text as a substring of title and description and applies the other query fields; paging follows the same limit rule as real connectors, with a default page of 50.
FakeCodeHost
| Option | Default | Meaning |
|---|---|---|
id | "fake" | The connector's id. |
type | "fake" | Reported as host.type. |
repos | none | Repositories; only name is required. fullName defaults to fake/<name>, defaultBranch to main, cloneUrl to https://git.test/fake/<name>.git. |
pullRequests | none | Merged pull requests, served newest first and filtered by mergedSince. |
auth | none | What gitAuth() returns. |
capabilities | pull-requests, remote-head | Remove pull-requests to test a host without history. |
remoteHeads | none | Answers of getRemoteHead, keyed <repo>@<branch>. |
Listing, links.refresh and ownership work on it as they are. repos.sync() would run git clone on the placeholder URL: for a sync test, give each repo a cloneUrl that is an absolute directory path. Safran then reads it in place, as it does for a local host.
FakeDocSource
| Option | Default | Meaning |
|---|---|---|
id | "fake" | The connector's id. |
type | "fake" | Reported as source.type. |
origin | https://docs.test | The origin whose URLs it claims. Compared as a parsed origin, as a real source must. |
pages | none | Pages by full URL: title, content, optionally updatedAt and author. |
A URL on its origin that it has no page for is NOT_FOUND. addPage(url, page) adds one; calls records getPage calls.
FakeCodeIndex
| Option | Meaning |
|---|---|
embedder | What status().embedder reports. Default fake:hash-256. |
files | Repo name → repo-relative path → file text. These repos count as indexed from the start. |
groups | Group → repo names, for status(). |
hits | Scripted search results: a list, or a function of the query. Filters and limit still apply. Without it, search is a word match over files. |
repos | Extra status() rows, for repos without files here. |
Beyond the CodeIndex methods it has switches for the situations that are hard to produce for real:
| Member | Use |
|---|---|
calls, count(method), last(method) | What the index was asked. last returns the arguments of the latest call. |
addFile(repo, path, text), files | Change the content between calls. |
hits | Replace search results with scripted ones. |
grepResult | Make grep answer this, for example a result with incomplete. |
failure | When set, every method except close throws it. |
hang | While true, search, grep and indexRepo only settle when their signal aborts. For cancellation and timeout tests. |
failOn | Repo names whose indexRepo fails with UPSTREAM, for testing a sync report with a failed row. |
indexed | What indexRepo was last given, by repo name. |
closed | Number of close() calls, to assert on index ownership. |
Its limits are its own (10 hits, 50 grep matches, 200 lines per read, 400 at most) and are exported as DEFAULT_FAKE_* constants. They mirror the real defaults, but the real index also clamps at maximums the fake does not have.
Remember that the instance resolves groups from the profile before it calls the index, so the group names in a test come from the profile's code.groups.
FakeEmbedder
new FakeEmbedder() is an Embedder with id fake:hash-256. It hashes word tokens and character trigrams into a 256-dimensional unit vector: the same text always gives the same vector, and texts that share words land close together. embedded counts the texts it was asked for, which makes caching testable.
It lets you run the real index in a test, which covers scanning, chunking, incremental indexing and the lexical channel without an embedding server:
import { expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createSafran, defineProfile } from "@safran/core";
import { FakeEmbedder } from "@safran/kit/testing";
test("sync indexes a local repository and search finds it, without an embedding server", async () => {
const root = mkdtempSync(join(tmpdir(), "acme-index-"));
mkdirSync(join(root, "payments-api/src/refund"), { recursive: true });
writeFileSync(join(root, "payments-api/src/refund/policy.ts"), "export class RefundPolicy {\n roundRefundAmount(amount: number): number {\n return Math.round(amount * 100) / 100;\n }\n}\n");
const embedder = new FakeEmbedder();
await using safran = await createSafran({
profile: defineProfile({
version: 1,
company: "acme",
code: { hosts: [{ id: "disk", type: "local", repos: [{ name: "payments-api", path: join(root, "payments-api") }] }] },
}),
dataDir: join(root, "data"),
embedder,
});
const first = await safran.repos.sync();
expect(first.results.map((row) => row.status)).toEqual(["ok"]);
expect(first.results[0]?.index?.filesIndexed).toBe(1);
const embeddedOnce = embedder.embedded;
expect(embeddedOnce).toBeGreaterThan(0);
// Nothing changed: the second sync re-chunks and re-embeds nothing.
const second = await safran.repos.sync();
expect(second.results[0]?.index).toMatchObject({ filesIndexed: 0, filesUnchanged: 1, embeddingsComputed: 0 });
expect(embedder.embedded).toBe(embeddedOnce);
const { hits } = await safran.code.search("RefundPolicy", { mode: "lexical" });
expect(hits[0]).toMatchObject({ repo: "payments-api", path: "src/refund/policy.ts" });
expect((await safran.code.status()).embedder).toBe("fake:hash-256");
});The test searches with mode: "lexical" on purpose: the lexical channel is the real one, while a dense ranking made of hashed words would prove nothing.
The fake plugins
createSafran builds connectors from profile entries, so the fakes reach it as plugins of type fake:
fakePlugins field | Connectors for |
|---|---|
trackers | trackers[] entries with type: fake, matched by id. |
hosts | code.hosts[] entries, matched by id. |
docs | docs[] entries, matched by id. |
embedder | The embeddings entry. Without it, each build gives a new FakeEmbedder. |
fakePlugins(connectors) returns all four plugins at once. Every profile entry of type fake needs a connector with the same id; one that is missing fails creation with a message that says "Test setup: no fake tracker for profile entry …", so a fixture mistake does not look like a product bug.
The single-kind helpers take more forms:
| Call | Result |
|---|---|
fakeTrackerPlugin(tracker) | That one tracker serves every fake tracker entry. |
fakeTrackerPlugin([a, b]) | Trackers matched to entries by id. |
fakeTrackerPlugin({ tickets }) | A new FakeTracker per entry, taking the entry's id. |
fakeCodeHostPlugin(...) | The same three forms for code hosts. |
fakeDocSourcePlugin(source) or ([a, b]) | One source, or several matched by id. |
fakeEmbedderPlugin(embedder?) | The given embedder, or a new FakeEmbedder per build. |
Each takes a second argument, { type, onCreate }: type registers the plugin under another type name (to stand in for jira in a profile you do not want to edit, together with builtinPlugins: false), and onCreate(config, context) is called on every build, which is how a test captures the PluginContext or checks that a secret is read the way a real connector reads it.
The fake plugins accept any extra keys in a profile entry (projects, include, made-up fields), so a test profile does not have to satisfy a real connector's schema.
Common mistakes
| Symptom | Cause |
|---|---|
INTERNAL: Test setup: no fake tracker for profile entry "jira" | fakePlugins got no connector with that id. |
NOT_FOUND: No tracker recognises "PAY-1" in a test | The FakeTracker has no ticket in project PAY and no projects option. |
| A test hangs | index.hang = true without a signal, or an await using instance waiting for a call that ignores cancellation. |
| A retry test takes seconds | The retried reply has no retry-after: 0 header, so the real backoff runs. |
| Tests influence each other | They share a dataDir (one links store) or one fake instance. Build both per test. |
| A ranking assertion that passes on fakes and fails for real | Fakes do not rank by meaning. Assert on what was asked, not on which file came first. |