Test it end to end
The round trip nestrs g resource wrote boots the real BlogModule on a throwaway database; add two failure modes beside it and run them.
You finish the e2e test nestrs g resource wrote on page 2: it boots the
real BlogModule against a throwaway Postgres, drives it through the same
transport production runs, and asserts on the round-trip you’ve been verifying
by hand. By the end of this page, nestrs run test e2e runs it green beside
two failure modes, a wiring regression in any of the previous pages fails it,
and the feature is locked down.
One e2e suite per app
Section titled “One e2e suite per app”Every app ships one tests/e2e/main.rs. Cargo compiles it as a separate
binary; nextest gates it through a binary filter, not #[ignore]. Its
main.rs holds the module list and the fixtures every test shares, and each
test file sits beside it — posts.rs for the posts feature.
The crate driving this page is
nest-rs-testing —
it provides TestApp (the in-process boot harness) and the throwaway
database it boots on, created and dropped per test.
That database needs a reachable Postgres, not a container runtime: the
harness reads <PREFIX>_SEAORM__URL from the project’s .env cascade — under
<PREFIX>_ENV=test, the scaffold’s .env.test names compose.yml’s — issues a
CREATE DATABASE nest_rs_e2e_… against that server, migrates it, and drops it
once the app is gone. Whatever provides that server — the devcontainer’s
compose.yml, a service container in CI, a local install — is your choice.
When the suite cannot connect, <PREFIX>_SEAORM__URL is what to check.
Directoryapps/blog/
Directorytests/
Directorye2e/
- main.rs the fixture
- posts.rs the tests
nestrs g resource added the dev-dependencies the suite names:
[dev-dependencies]nest-rs = { workspace = true, features = ["testing"] }tokio.workspace = truemigrations = { workspace = true }serde_json = { workspace = true }uuid = { workspace = true }testing brings TestApp in on the app’s dev-dependency alone, so no release
binary carries the harness; its throwaway database rides the workspace’s
seaorm feature, and its signing key the authn one. migrations is the
workspace’s migrator, serde_json writes the request bodies, and uuid the
subject a token names. A suite never runs main, so it exports no telemetry:
it logs through the console the boot installs.
The boot harness
Section titled “The boot harness”TestApp::builder() runs the same four-phase boot as main, including the
access-graph check, on the module main boots — its guards and every other
app-wide layer it declares come with it. ephemeral_database creates the
throwaway database, migrates it, seeds its connection as the app’s pool and
drops it after the app. ephemeral_signing_key has the app verify the tokens
of a key pair the test holds, issued for that boot, in place of the secret
.env.test names — so the suite signs a token the guards admit without
spelling a key. The generator wrote the one fixture every test shares:
//! The app's suite against a throwaway database: every test boots the//! composition `main` runs, migrated by the workspace's migrator, and signs//! the tokens it sends with a key of its own.
mod posts;
use nest_rs::testing::TestApp;
use blog::BlogModule;
pub(crate) async fn boot() -> TestApp { TestApp::builder() .module::<BlogModule>() .ephemeral_database::<migrations::Migrator>() .ephemeral_signing_key() .build() .await .expect("BlogModule boots against a throwaway database")}The test binary imports BlogModule from a blog library target, which
the scaffold wrote on page 1 — Cargo auto-detects src/lib.rs and
src/main.rs, so the manifest needs no [lib] or [[bin]] section:
mod module;
pub use module::BlogModule;The round trip, and two failures
Section titled “The round trip, and two failures”Because the controller is guarded, every request carries a bearer, and
app.bearer signs it with the key the boot installed: a token over your own
Claims, for the audience and from the issuer the app requires, which its
guard admits, living as long as one the app would mint.
The generated posts_round_trip posts a value of each column you named on
page 2 and reads each back. Add two negative paths beside it — the 400 you
met in Validate inputs, and the 401 of a call with
no token:
use nest_rs::http::StatusCode;use serde_json::json;use uuid::Uuid;
use features::authn::{Claims, Role, Subject};
use crate::boot;
fn bearer(app: &nest_rs::testing::TestApp) -> String { app.bearer(&Claims { sub: Subject::User(Uuid::now_v7()), client_id: "e2e".into(), roles: vec![Role::User], })}
#[tokio::test]async fn posts_round_trip() { let app = boot().await; let bearer = bearer(&app);
let created = app .http() .post("/posts") .header("authorization", &bearer) .body_json(&json!({ "title": "Title 1", "body": "Body 1" })) .send() .await; created.assert_status(StatusCode::CREATED); let created = created.json().await; let id = created.value().object().get("id").string().to_owned();
let read = app .http() .get(format!("/posts/{id}")) .header("authorization", &bearer) .send() .await; read.assert_status_is_ok(); let read = read.json().await; let fields = read.value().object(); assert_eq!(fields.get("title").string(), "Title 1"); assert_eq!(fields.get("body").string(), "Body 1");}
#[tokio::test]async fn create_with_empty_title_returns_400() { let app = boot().await; app.http() .post("/posts") .header("authorization", bearer(&app)) .body_json(&json!({ "title": "", "body": "Body 1" })) .send() .await .assert_status(StatusCode::BAD_REQUEST);}
#[tokio::test]async fn create_without_a_token_returns_401() { let app = boot().await; app.http() .post("/posts") .body_json(&json!({ "title": "Title 1", "body": "Body 1" })) .send() .await .assert_status(StatusCode::UNAUTHORIZED);}The bearer moved into a function the three tests share, beside them in the
file that needs it. The assertions cover the entire chain: the POST walks
validation, the unit of work’s transaction, and the service; the
GET /posts/{id} walks CrudService::access through Repo.
Run it
Section titled “Run it”nestrs run test e2e is the recipe; it routes to nextest with the binary
filter for the e2e suite.
-
Keep Postgres up — the
compose.ymlservices you started in Persist through Postgres. The suite migrates its own throwaway database, so it needs nonestrs run db up.Terminal window $ docker compose up -d✔ Container hello-postgres-1 Running✔ Container hello-redis-1 Running✔ Container hello-storage-1 Running -
Run the e2e suite.
Terminal window $ nestrs run test e2e────────────Starting 3 tests across 1 binaryPASS [ 1.4s] blog::e2e posts::posts_round_tripPASS [ 0.8s] blog::e2e posts::create_with_empty_title_returns_400PASS [ 0.7s] blog::e2e posts::create_without_a_token_returns_401
nestrs run test e2e and nestrs run test integration, whose suites need no
database, are the two recipes you reach for day to day; nestrs run test unit
runs the #[cfg(test)] modules, nestrs run test doc the /// examples,
nestrs run test cov adds coverage, and bare nestrs run test runs every kind.
What you have now
Section titled “What you have now”- A
tests/e2e/suite booting the realBlogModuleagainst a throwaway database created on the Postgres<PREFIX>_SEAORM__URLnames. - A happy path, a validation failure and an unauthenticated call — enough to catch a wiring regression in any of the previous pages.
- A
nestrs run test e2erecipe running them green.
Going further
Section titled “Going further”- Authenticate and authorize — the next step: read the policy on
api, before you narrowblog’s. - E2E tests — the reference page for
TestApp, its throwaway database, the bearer it signs and the unit it runs a service in.