Testing
Test RLS, APIs and SQL against the local stack as real users.
better-supabase/testing signs tokens with the local stack's ES256 signing
key, the same kind of key a hosted project uses. The same user then works
through PostgREST, direct Postgres and your API, so tests exercise the real
RLS policies instead of mocks.
Without Docker, liteStack() runs Supabase Lite
inside the test process on in-memory SQLite or PGlite, with the same
asUser and RLS, as long as the schema stays within what Lite supports.
Signing key
Create the key once with better-supabase dev keys. It writes
supabase/signing_keys.json and warns until the file is in .gitignore.
Point supabase/config.toml at it and restart the stack, so Auth signs with
it and the JWKS publishes it:
[auth]
signing_keys_path = "./signing_keys.json"pnpm better-supabase dev keys
supabase stop && supabase startasUser
import { asUser } from "better-supabase/testing";
const alice = await asUser(
betterSupabase,
{ sub: aliceId, tenant_id: acme },
{ postgres },
);
expect(await alice.db.customers.count().orThrow()).toBe(3);
expect(await alice.sql!.customers.count().orThrow()).toBe(3);
await alice.supabase.storage.from("customer-logos").list(acme);asUser reads the URL and publishable key from the environment, with or
without a framework prefix, just as better-supabase dev env
writes them. It signs with the first key in the file signing_keys_path
points to (or $SUPABASE_SIGNING_KEYS_PATH); pass signingKey to use
another. db goes through PostgREST, and sql goes through direct Postgres
with the same claims, when you pass postgres.
A stack without a signing key still verifies tokens signed with the shared
JWT secret. Pass { alg: 'HS256' } to sign that way; it reads
SUPABASE_JWT_SECRET and refuses any URL that is not local.
supabase-js warns when its trace propagation option is on and the runtime
has no OpenTelemetry tracing loaded. Test users switch it off; pass
{ tracePropagation: true } to keep it.
Sign in through Auth
asSignedInUser(betterSupabase, { email, password }, stack) takes the access
token from the stack's Auth (/auth/v1/token, the password grant) instead of
signing its own. The token carries what Auth puts there, including the claims
a custom access token hook adds, and claims and context are read from it.
The user must exist, for example from the seed. It throws a TypeError that
names the email when Auth refuses.
import { asSignedInUser } from "better-supabase/testing";
const alice = await asSignedInUser(betterSupabase, {
email: "alice@acme.test",
password: "password",
});signLocalJwt(claims) signs a token the same way without building
repositories, for requests you send yourself.
Command tests
alice.context is the server RequestContext for the user: the actor and
the claims asUser signed. Together with alice.supabase and alice.db it
builds the request a command or handler receives, so a test calls the
function directly and RLS still applies:
import { asUser } from "better-supabase/testing";
import { archiveCustomer } from "./archive-customer";
const alice = await asUser(betterSupabase, { sub: aliceId, tenant_id: acme });
await archiveCustomer(
{ supabase: alice.supabase, db: alice.db, context: alice.context },
{ id: customerId },
);The token is alice.token. Send it as Authorization: Bearer when the
command sits behind a route and you call the route over HTTP instead.
Isolation between tests
Tests that run at the same time must not share rows. These helpers cover the ways to do that:
| Helper | Isolates with | Covers |
|---|---|---|
scopedSeed(betterSupabase, build) | A fresh tenant and rows per test, deleted after | db over PostgREST, sql |
withRollback(user, fn) | One transaction that always rolls back | sql only |
withClaims(postgres, claims, fn) | One transaction that always rolls back | raw SQL as a user |
scopedSeed creates a new tenant id, inserts the fixtures that build
returns through the service role, and returns the inserted rows.
cleanup() (or await using) deletes them in reverse order, the tenant row
last. It needs stack.secretKey or $SUPABASE_SECRET_KEY. Use id() for
rows that other fixtures reference:
import { test } from "node:test";
import { asUser, scopedSeed } from "better-supabase/testing";
test("lists the tenant's customers", async () => {
await using scope = await scopedSeed(
betterSupabase,
({ tenant }) => ({
memberships: {
alice: { organizationId: tenant, userId: aliceId, role: "member" },
},
customers: { first: { organizationId: tenant, name: "First" } },
}),
{
tenant: {
table: "organizations",
row: (id) => ({ id, name: id, slug: id }),
},
},
);
const alice = await asUser(betterSupabase, {
sub: aliceId,
tenant_id: scope.tenant,
});
expect(await alice.db.customers.count().orThrow()).toBe(1);
});Seed the user's membership as well: the access contract trusts the
tenant_id claim only when the user is a member of that tenant, so a claim for
a tenant without one reads nothing. Under the catalog model, role holds the
role's id from better_supabase.roles.
node:test runs the tests of one file one after another and the files in
parallel, and each call gets its own tenant, so the files never see each
other's rows. Give the tenant row a unique slug or name, as above.
withRollback(alice, fn) runs fn as the user inside one transaction over
direct Postgres, passes it the same repositories as alice.sql, and rolls
back when fn returns or throws. It returns what fn returned. It needs
asUser to have been given postgres, and throws a clear error otherwise.
Rollback covers only that sql path: alice.db talks to PostgREST over
HTTP and commits on its own, so a write through db stays.
const alice = await asUser(betterSupabase, claims, { postgres });
const count = await withRollback(alice, async (db) => {
await db.customers.create({ organizationId: acme, name: "Temp" }).orThrow();
return db.customers.count().orThrow();
});withClaims(postgres, claims, fn) does the same for raw SQL, without
asUser. It runs fn with a SqlClient inside one transaction that sets
role (from claims.role, else authenticated) and request.jwt.claims,
so auth.uid(), auth.jwt() and RLS answer as they would for that user, and
it always rolls back:
import { createPostgres } from "better-supabase/postgres";
import { withClaims } from "better-supabase/testing";
const postgres = createPostgres({
connectionString: process.env.SUPABASE_DB_URL,
});
await withClaims(postgres, { sub: aliceId, tenant_id: acme }, async (sql) => {
const [row] = await sql.queryRaw<{ id: string }>("select auth.uid() as id");
expect(row?.id).toBe(aliceId);
});Jest and jest-expo
better-supabase ships ES modules only, on purpose, so Jest has to transform
it. Add it to the allow-list of transformIgnorePatterns (Jest skips
node_modules by default), next to the packages your preset already lists:
module.exports = {
preset: "jest-expo",
transformIgnorePatterns: [
"node_modules/(?!(?:.pnpm/)?((jest-)?react-native|@react-native(-community)?|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|better-supabase))",
],
};Under the jsdom environment, older Jest releases have no TextEncoder or
TextDecoder global. better-supabase creates them when it first decodes a
session, not on import, so importing the client works either way. If a test
decodes a session in such an environment, polyfill both before it runs, for
example in setupFiles with the ones from node:util. The same applies to
Expo.
Fixtures
Share rows between supabase db reset and your tests with a
typed seed:
import { seed } from "../supabase/seed.ts";
beforeAll(() => seed.insert(postgres.admin));
const alice = await asUser(betterSupabase, {
sub: aliceId,
tenant_id: seed.rows.organizations.acme.id,
});A tenant seed fills one tenant from its id, so a test can give each organization it creates the same rows:
import { seed as tenantSeed } from "../supabase/seed.tenant.ts";
const { id } = await organizations.create({ name: "Test org" }).orThrow();
await tenantSeed.insert(postgres.admin, { id });supabaseClaimFixtures holds access-token claims where someone acts for the
user, with the created-by, impersonator and delegation each one reads as:
supportSession, supportSessionReadOnly, impersonation, oauthClient,
agentChain, agentRun and agentRunReadOnly. supabaseInvalidClaimFixtures
holds the claims better-supabase refuses (the 0.5.0 support token and
malformed act levels), each expecting an invalid session with code
ACTOR_INVALID. They follow the claim contract every hook writes, so a test
can sign one and check a guard or a support banner. A library that reads the
same claims can call actorOf and delegationOf from better-supabase/server
on each fixture for a parity test:
import {
createTestSigner,
supabaseClaimFixtures,
} from "better-supabase/testing";
const signer = await createTestSigner();
const token = await signer.sign(supabaseClaimFixtures.supportSession.claims);Impersonation lists what
each act.kind means.
Factories
factories() from better-supabase/generators/factories writes <output>.factories.ts,
with one factory per table that returns a valid insert row. Defaults follow
enums, CHECK bounds and StoragePath buckets, a foreign key takes the parent
row or its id, and a column without a safe default is a required input.
Block entities also get a factory under their final singular noun, such as
factories.task.
import { defineConfig } from "better-supabase/config";
import { factories } from "better-supabase/generators/factories";
export default defineConfig({ gen: { generators: [factories()] } });import { factories } from "@/lib/supabase/generated.factories";
const acme = await alice.db.customers.create(factories.customers()).orThrow();
const task = factories.tasks({ customerId: acme, title: "Call back" });
const many = factories.tasks.many(20, { customerId: acme });
await factories.tasks.create(alice.db.tasks, { customerId: acme });Each call numbers its row, and text and uuid defaults include that number, so
rows from one factory differ. many(count, input) builds a list, and create(repository, input) passes
the row to a repository's create. tables limits the file to some tables,
and testingImport changes where it imports defineFactory and
factoryTime from (better-supabase/testing by default). Both are exported
for factories you write by hand.
APIs
ES256 test tokens verify against the local stack's JWKS, so your framework adapter needs no test-only resolver and sees the same claims that RLS sees:
const bsb = createHono(betterSupabase);
await app.request("/api/customers", {
headers: { authorization: `Bearer ${alice.token}` },
});For HS256 tokens, add localAuth(secret) to auth.resolvers. Use it in
tests only.
Hermetic server tests
A unit test that builds its own server should not depend on the variables your shell exports or the stack that happens to be running. Pass the variables as an object, and the keys inline:
import { createServer } from "better-supabase/server";
import { createTestSigner } from "better-supabase/testing";
const signer = await createTestSigner();
const bsb = createServer(betterSupabase, {
env: {
SUPABASE_URL: "http://127.0.0.1:54321",
SUPABASE_PUBLISHABLE_KEY: "sb_publishable_test",
},
auth: { jwks: signer.jwks },
});
const ctx = await bsb.context(
new Request("https://app.test/", {
headers: { authorization: `Bearer ${await signer.sign({ sub: aliceId })}` },
}),
);An env object is the only source the server reads: SUPABASE_JWKS or a
stale SUPABASE_URL in process.env is ignored. With auth: { jwks: false }
no key is looked up at all, so every ES256 token resolves as invalid.
createServer lists the full order.
Authorizers
staticAuthorizer is an in-memory authorizer
for tests and examples. Permissions come from the subject's role and id,
never from the request's resource or context:
import { staticAuthorizer } from "better-supabase/testing";
const authorizer = staticAuthorizer({
roles: {
authenticated: ["customers.read"],
service_role: ["customers.delete"],
},
grants: { [alice.id]: ["customers.delete"] },
approvals: ["invoices.void"],
});
const bsb = createHono(betterSupabase, { authorizer });| Option | What it grants |
|---|---|
roles | Permissions per role: the subject's role property (the Postgres role, such as authenticated), or its type (anon) |
grants | Permissions per subject id, on top of the role's |
approvals | Permissions that answer approval-required, with the approval id approval:<permission> |
Anything else is denied. To check an authorizer of your own, run
testAuthorizer (see Conformance).
Tenant isolation
expectTenantIsolation(betterSupabase, { tenants, tables }) checks that RLS keeps two
tenants apart. For each table it seeds one row per tenant through the service
role, then signs in as a user of each tenant and tries to select, insert,
update and delete the other tenant's row:
import { expectTenantIsolation } from "better-supabase/testing";
it("keeps organizations apart", async () => {
await expectTenantIsolation(betterSupabase, {
tenants: [
{ id: ACME, name: "acme", claims: { sub: alice, tenant_id: ACME } },
{ id: GLOBEX, name: "globex", claims: { sub: bob, tenant_id: GLOBEX } },
],
tables: {
tags: {
row: (tenant, n) => ({ organizationId: tenant.id, name: `iso-${n}` }),
update: { color: "red" },
},
},
seed: () => seed.insert(postgres.admin),
});
});- A leak is a row that comes back from a select, or an insert, update or delete that changed the other tenant's data. The helper checks the row through the service role, so a blocked update that returns 0 rows counts as blocked.
- Each user must also read its own row. Otherwise the test passes because the user can see nothing, and the helper fails with a hint about claims and memberships.
row(tenant, n)builds a row owned bytenant.nis 0 for the seeded row and 1 for the insert attempt, so put it in unique columns.updatemust change the row.- It runs without
betterSupabase's plugins and extensions, so the memberships extension can't hide a missing policy. - On a leak it throws a
ConformanceErrornaming every table and command that leaked, such astags: globex can't delete leaky's rows. It removes every row it created either way. - It needs the service-role key:
stack.secretKeyor$SUPABASE_SECRET_KEY.
doctor reports tenant tables whose policies skip
a command before a test has to.
Services in a shared fill
inTenantFill(ctx, tables, body) runs body with the context a
share: "tenant" fill of bsb.kept() hands it, and returns its value with
the first refused read. Use it to check that an app's own service, given a db
through shareGuard,
reads only the entry's tables:
import { shareGuard } from "better-supabase/server";
import { inTenantFill } from "better-supabase/testing";
const fill = await inTenantFill(ctx, ["customers"], (shared) =>
customerService(shareGuard(shared, appDb)).page(organizationId),
);
expect(fill.refused).toBeUndefined();Database budget
expectDbBudget(page, { maxCalls, maxWaves, maxVerifications, maxAdminCalls, during }) fails a Playwright
test when one render makes more database calls, sequential waves, token verifications or
service-role calls than allowed. It reads the request id from every document and _rsc response
during during (a reload by default) and fetches each render's totals from
bsb.debugRoute():
import { expectDbBudget } from "better-supabase/testing";
const renders = await expectDbBudget(page, {
maxCalls: 8,
maxWaves: 2,
during: () => page.goto("/customers"),
});The failure lists each render over budget with its tables, so the diff that
added a query shows up in the message. The page type is structural, so
Playwright stays your dependency, not better-supabase's. The app needs
createNext(betterSupabase, { debug: { enabled: true } }) for the test build.
A response the browser aborts mid-stream (the router does this for some
navigations) counts as finished, so the check doesn't wait out timeoutMs
for it. After during resolves, the check keeps listening until no new
response has arrived for settleMs (500 ms by default), so a render that
starts late, such as the dynamic render after an instant() lock releases,
is still counted.
Instant navigations
expectInstant(page, { during, visible, absent, maxCalls, maxWaves }) runs
during inside @next/playwright's
instant(),
then checks what the prefetched UI shows while the lock still holds: every
visible locator must be visible, and every absent locator must match
nothing. With maxCalls or maxWaves it also checks the navigation's
database budget, as expectDbBudget does, and returns the measured renders.
import { expect, test } from "@playwright/test";
import { expectInstant } from "better-supabase/testing";
test("customers come from the per-session App Shell", async ({ page }) => {
await page.goto("/");
const link = page.getByRole("link", { name: "Customers", exact: true });
await expect(link).toBeVisible();
await expectInstant(page, {
during: async () => {
await link.click();
await page.waitForURL((url) => url.pathname === "/customers");
},
visible: [
page.getByRole("heading", { name: "Customers" }),
page.getByText("Road Runner Inc"),
],
maxCalls: 8,
maxWaves: 2,
});
});- Install
@next/playwrightas a dev dependency. It is an optional peer thatexpectInstantloads when it runs, so apps that never call it don't need it. - The app needs a
next buildwithexperimental.exposeTestingApiInProductionBuild; without it the lock is ignored and the check passes without testing anything. The budget options also needdebug.enabledandbsb.debugRoute(), as above. - A missing
visiblelocator fails aftertimeoutMs(5 seconds by default) with the locator in the message. Content that should stream in after the navigation, such as a count read per request, goes inabsent(absent: [page.getByTestId("unread-summary")]); assert it withexpectafterexpectInstantreturns. - Pass
baseURLwhenduringloads the first page, so the lock can be set before the page has a URL. - With
maxCallsormaxWaves, a navigation that never reaches the proxy fails: the client cache served it, so there is no render to measure. Drop the budget for that navigation;visiblealready proves it is instant.
Fake client
createFakeClient(handler) from better-supabase/testing stands in for the supabase-js client in unit tests. The handler answers each request and the client records it in requests, with the method, path, query and body:
import { createFakeClient } from "better-supabase/testing";
const client = createFakeClient(({ method, path }) =>
method === "GET" && path === "/customers"
? { data: [{ id: "c1", name: "Acme" }] }
: { data: null },
);
await client.from("customers").select("*").eq("name", "Acme");
await client.schema("api").rpc("end_sessions", { p_user: "u1" });
client.requests.map((request) => request.path);
// ["/customers", "/rpc/end_sessions"]It covers from, rpc, schema, the common filters, .single() and .maybeSingle(). A miss on .single() is PGRST116, as on a real server. Pass the client where a SupabaseClient is expected, with a cast in the test. Test tokens come from signTestJwt and createTestSigner (see Signing key).
createFakePostgrest(handler) answers at the fetch level, so the real
supabase-js client runs, with its URL building, headers and error handling.
The handler takes the same request and returns the same reply as
createFakeClient. Pass fetch to createClient's global.fetch or to
asUser's fetch option, and read requests for what it saw. It answers
Prefer: count=exact with a Content-Range header, and .single() with a
406 and PGRST116 unless exactly one row matches.
import { createClient } from "@supabase/supabase-js";
import { createFakePostgrest } from "better-supabase/testing";
const api = createFakePostgrest(() => ({ data: [{ id: "c1" }], count: 1 }));
const supabase = createClient(url, key, { global: { fetch: api.fetch } });
await supabase.from("customers").select("id", { count: "exact" });
api.requests[0]?.query; // { select: "id" }pgTAP
better-supabase add pgtap writes
supabase/tests/000_better_supabase_pgtap.test.sql. It runs first and
installs helpers that later test files can use with supabase test db:
begin;
select plan(2);
select tests.rls_enabled('public');
select tests.authenticate_as(tests.create_user('alice@example.com'), '{"tenant_id": "00000000-0000-4000-8000-000000000001"}');
select is((select count(*) from public.customers where organization_id <> '00000000-0000-4000-8000-000000000001'), 0::bigint, 'no cross-tenant rows');
select * from finish();
rollback;| Helper | Does |
|---|---|
tests.create_user(email, app_metadata, user_metadata) | Inserts a confirmed user and returns its id; call it before switching roles |
tests.authenticate_as(user_id, claims) | Switches to authenticated with the user's claims for the rest of the transaction |
tests.authenticate_as(email) | The same for the user with that email address; fails when there is none |
tests.authenticate_as_issued(user_id, hook) | Runs the custom access token hook and signs in with the claims it adds; hook defaults to the one in config.toml |
tests.act_as(role, user_id, claims) | Switches to any role with the given sub and claims for the rest of the transaction |
tests.visible_row_count(relation, filter) | Counts the rows the current role sees in a relation, with an optional where text; RLS applies |
tests.authenticate_as_anon() | Switches to anon |
tests.clear_authentication() | Switches back to the test runner's role |
tests.every_table_has_rls(schema) | Fails and lists every table in the schema without row level security (tests.rls_enabled is the same check) |
tests.policies_use(schema, pattern) | Fails and lists every policy whose using and with check expressions don't match the regular expression |
tests.no_anon_policies(schema) | Fails and lists every policy that applies to anon, by name or through public |
tests.every_table_audited(schema, exempt) | Fails and lists every table without an audit trigger; exempt holds like patterns for table names |
tests.partitions_have_rls(schema) | Fails and lists every partition of an RLS table that has RLS off, the default partition included |
The helpers stay installed after the run, so supabase db advisors sees
them too. Each one sets its own search_path, so the advisors report no
function_search_path_mutable warning for them; run upgrade after
upgrading to rewrite a module file from an earlier version.
authenticate_as_issued reads auth.hook.custom_access_token from config.toml when gen writes the file, so a test sees the claims a real sign-in gets, such as the tenant or the permissions. Without a hook in config.toml it raises an error that names the setting, unless the test passes the hook.
With the audit block installed, supabase/tests/900_better_supabase_audit.test.sql is one file that loops over the audited tables and keeps one assertion name per table. sql upgrade deletes the older 900_better_supabase_audit_<table> files.
Last updated on
Contexts for every entry point
Build the same ServerContext from a request, a resolution, an auth state or a cron call, and write scheduler routes with cronHandler.
Monorepos
One runtime package owns createSupabase and the request context; domain packages type their repositories from its db and never import the generated client.