End-to-end tests
TestApp boots the real ApiModule on a throwaway database and a key of the test's own — routes, DI graph, access graph, guards and data path all run.
An end-to-end test boots the real top-level module in process,
against a throwaway Postgres database, and drives the HTTP surface
through the same transport production runs. Every app ships one, at apps/<app>/tests/e2e/main.rs
— the same tests/<suite>/main.rs directory form as every test binary
in the codebase (see Integration tests for the
layout rule). The happy path covered here pairs with
negative-path tests — auth refused,
cross-tenant denied, rollback verified — for the bugs a 2xx round-trip
never trips.
A round-trip e2e test
Section titled “A round-trip e2e test”use api::ApiModule;use features::{Role, Subject};use nest_rs::testing::{TestApp, TestAppBuilder, TestResponse};// …
pub(crate) async fn boot() -> TestApp { boot_with(TestApp::builder()).await}// …
async fn boot_with(builder: TestAppBuilder) -> TestApp { builder .module::<ApiModule>() .ephemeral_database::<migrations::Migrator>() .ephemeral_signing_key() .build() .await .expect("ApiModule boots against a throwaway database")}
pub(crate) fn sign(app: &TestApp, org_id: Uuid, role: Role) -> String { app.bearer(&claims(org_id, role, client()))}The suite boots ApiModule, the module the api’s main boots, and nothing
beside it: every route runs behind the guards the binary puts in front of it, its
controller’s and any pool that module’s providers list, and the OpenAPI document
describes them. The boot also arms the
app’s outbox, as the binary’s relay does, so what a test pushes waits in the
throwaway database
(a job pushed inside a transaction). Each test gets
a database of its own, created and migrated at the boot and dropped after the
app, and the app verifies the tokens of a key the test holds, so sign mints a
bearer the guards admit (a bearer the app verifies). Nothing else is
configured: the api reads its audience from its own .env layer and its issuer
from the root’s, as nestrs run dev does.
Each test module reaches for that boot() and the sign helper beside it:
use nest_rs::http::{StatusCode, header};// …use serde_json::json;// …use crate::*;
#[tokio::test]async fn users_are_scoped_to_their_org_and_bound_by_id() { let app = boot().await;
let bootstrap = sign(&app, ORG_ID, Role::Admin); let org_a = create_org(&app, &bootstrap, "Acme").await; // … let token_a = sign(&app, org_a, Role::Admin); // …
let created = app .http() .post("/users") .header(header::AUTHORIZATION, &token_a) .body_json(&json!({ "name": "Ada", "email": "ada@acme.test" })) .send() .await; created.assert_status(StatusCode::CREATED); // …}TestApp::builder().module::<ApiModule>() runs the same
four-phase boot as main, including the access-graph check. A wiring
regression fails this test, in this binary.
Splitting a large suite
Section titled “Splitting a large suite”main.rs is the suite root — the mod list and the fixtures the siblings
share — and each concern is a sibling module, so the path never changes as
the suite grows. Cargo
auto-detects tests/e2e/main.rs as a single integration-test binary
named e2e, and — unlike top-level tests/*.rs — it does not
compile the sibling files under tests/e2e/ as their own binaries. So
the whole subtree links into one e2e binary that the nextest
binary(e2e) gate still catches.
apps/api/└── tests/ └── e2e/ ├── main.rs ← the suite root: mod users; …, boot(), sign(), fixtures ├── users.rs ├── orgs.rs ├── posts.rs └── graphql.rsIts mod list is the suite’s index:
mod audio;mod audit;mod graphql;mod health;mod http;mod module;mod openapi;mod orgs;mod posts;mod schema;mod scopes;mod subscription;mod users;Each module pulls the shared setup with one line — use crate::*;, as in
the test above.
Because main.rs is the crate root, mod users; resolves to a sibling
tests/e2e/users.rs in the same directory, and the pub(crate) fixtures
beside the mod list are crate:: items every sibling reaches — nothing
under tests/e2e/ is auto-discovered as a binary.
Why one binary instead of tests/e2e_users.rs, tests/e2e_orgs.rs:
- The four-phase boot is the expensive part — sharing
boot()frommain.rskeeps it written once. - Cargo links the app crate once per binary; one binary means one link step instead of one per concern file.
nestrs run test e2eruns the whole suite from the workspace root.
Ephemeral Postgres
Section titled “Ephemeral Postgres”ephemeral_database::<Migrator>() is how a suite boots on a database: the
harness creates a uniquely-named Postgres database at the boot, runs the
migrations, seeds its connection in place of the pool SeaOrmModule would
open, and drops it after the app, closed or dropped — even on panic, and even
after a crashed previous run, whose nest_rs_e2e_* databases older than five
minutes the next boot reaps. The admin URL comes from <PREFIX>_SEAORM__URL,
and every connection the fixture opens is the app’s pool’s: TLS verified, or off
by sslmode=disable in the URL or libpq’s PGSSLMODE=disable beside a URL naming
no mode, an sslmode that encrypts without verifying refused.
pub(crate) async fn data_app() -> TestApp { TestApp::builder() .module::<DataModule>() .ephemeral_database::<migrations::Migrator>() .build() .await .expect("the data layer boots on a throwaway database")}A test that seeds rows, or boots a second app beside the first — a worker draining what the api filed — reads the connection back from the booted app’s container and writes through your own entities:
let conn = app .container() .get::<DatabaseConnection>() .expect("the app's pool is its throwaway database");let org = orgs::ActiveModel { id: Set(Uuid::now_v7()), name: Set("Acme".into()), ..Default::default()}.insert(conn.as_ref()).await?;EphemeralDatabase::create::<Migrator>() is the same database for a test that
boots no app — a migration run, a seed script — held by the value and dropped
with it.
A service in a unit
Section titled “A service in a unit”A service reads the executor and the ability its unit installs, so a test
calling one directly runs it in a unit of the app’s own binding:
app.unit(ability, || svc.list()) as a request granted ability,
app.system_unit(|| svc.purge_expired()) as a job. The unit commits on the
body’s Ok and rolls back on its Err, as an edge’s does — never an executor or
an ability installed by hand. It stands in for a unit naming its read, so a test of
a define_visitor grant hands it the visitor’s ability.
let app = data_app().await;let org_id = seed_org(&connection(app.container()), "Acme").await;
let rows = app .unit(read_all_ability(), || OrgsService.list()) .await .expect("list succeeds");unit and system_unit are nest-rs’s authz and database features
beside testing.
What ends an HTTP/GraphQL change
Section titled “What ends an HTTP/GraphQL change”E2E is not enough on its own. After the test goes green, run the binary
and curl the affected endpoint:
$ nestrs run dev api &$ curl -H "Authorization: Bearer $TOKEN" http://localhost:3002/users$ kill %1Stop the server when you’re done — kill %1, or the port stays
bound for the next run.
Going further
Section titled “Going further”- Driving the app — a bearer the app verifies, the HTTP client, and a GraphQL subscription without a socket.
- Provider overrides — swap a provider for a double before anything is built from it.
- Headless apps — a worker, its Redis database, the outbox relay and the way down.
- Negative-path tests — the failure modes a 2xx round-trip never trips.