NestJS e2e test for a sign-up verification email
NestJS ships with a standard end-to-end setup: Jest, supertest and Test.createTestingModule, with the application booted in memory by app.init(). This guide adds one test to that setup that proves the sign-up email really goes out. The Nest app sends its message through its real mailer, configured from environment variables. The test posts to the sign-up route with supertest, reads the email through AssertInbox with the CommonJS client, and then uses the code from the email to finish the verification. It targets NestJS 10 or newer, Jest 29 and Node 18 or newer. The test files are TypeScript.
Why not stub the mailer
A common Nest pattern is .overrideProvider(MailService).useValue(fake), which is fine for fast unit-style tests. It cannot tell you that the SMTP host is reachable, that the credentials in the environment are right, that the sender address is accepted, or that the template renders a real code. One end-to-end test with the real mailer covers those. Keep the stubbed tests for the many cases and add this one for the path that must work.
How it works
Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls and returns the newest matching message as JSON, including id, subject, otp and magic_link, or 408 if nothing arrived. Messages are deleted after 24 hours. Your mail provider delivers to assertinbox.com like to any other domain, so nothing in the app changes between a real user and a test.
Get an API key
Get one in a click at /start, or with the request below. One request creates a key and your private namespace. No email address or card is needed. The key is shown once, so keep it in your secret manager or CI secrets.
curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}
Export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (the namespace). If the call returns 403 signups_closed, the beta is not open for new keys. Use inboxes only for services you own or control; see the terms. Limits and error codes are on the limits page.
The app under test
This is a small Nest module you can replace with your own. MailService builds a Nodemailer transport from environment variables, AuthService keeps users in memory to stay short, and AuthController exposes POST /auth/register and POST /auth/verify. Install the packages with npm install @nestjs/common @nestjs/core @nestjs/platform-express nodemailer reflect-metadata rxjs. Save the three classes as src/auth.ts, together with the module.
import { Body, Controller, HttpCode, Injectable, Module, Post, BadRequestException } from "@nestjs/common";
import { createTransport } from "nodemailer";
import { randomInt } from "node:crypto";
@Injectable()
export class MailService {
private transport = createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT || 587),
secure: process.env.SMTP_SECURE === "true",
auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS } : undefined,
});
async sendCode(to: string, code: string) {
await this.transport.sendMail({
from: process.env.MAIL_FROM,
to,
subject: "Your verification code",
text: "Your verification code is " + code + ". It is valid for 15 minutes.",
});
}
}
@Injectable()
export class AuthService {
private users = new Map<string, { code: string; verified: boolean }>();
constructor(private readonly mail: MailService) {}
async register(email: string) {
const code = String(randomInt(100000, 1000000));
this.users.set(email, { code, verified: false });
await this.mail.sendCode(email, code);
}
verify(email: string, code: string) {
const user = this.users.get(email);
if (!user || user.code !== code) throw new BadRequestException("invalid_code");
user.verified = true;
return { verified: true };
}
}
@Controller("auth")
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post("register")
@HttpCode(202)
async register(@Body() body: { email: string }) {
await this.auth.register(String(body.email).toLowerCase());
return { ok: true };
}
@Post("verify")
@HttpCode(200)
verify(@Body() body: { email: string; code: string }) {
return this.auth.verify(String(body.email).toLowerCase(), String(body.code));
}
}
@Module({ controllers: [AuthController], providers: [AuthService, MailService] })
export class AuthModule {}
The mailer reads SMTP_HOST, SMTP_PORT, SMTP_SECURE, SMTP_USER, SMTP_PASS and MAIL_FROM when the service is constructed, so the same code works with a transactional provider in staging and with a local server on a developer machine. Send only from an address your provider has verified.
Install the client
Jest with ts-jest loads CommonJS, so use the CommonJS copy of the client. It is one file with no dependencies. Put it in the test folder next to the e2e spec and install the test tools:
npm install --save-dev jest ts-jest @types/jest supertest @types/supertest typescript
curl -o test/assertinbox.cjs https://assertinbox.com/sdk/assertinbox.cjs
The file exports AssertInbox. The methods used here are uniqueTag(), address(tag), waitForOtp() and delete(tag). Because the file is plain JavaScript, the spec loads it with require; Nest projects usually allow this because @types/node is installed.
The e2e spec
Save this as test/auth.e2e-spec.ts. The module is compiled with the real MailService, app.init() starts it in memory, and request(app.getHttpServer()) sends requests without opening a port. Each test builds its own tag, and afterEach deletes the messages even when the test fails. The import form import request from "supertest" needs esModuleInterop in tsconfig.json, which current Nest projects have by default.
import { Test } from "@nestjs/testing";
import { INestApplication } from "@nestjs/common";
import request from "supertest";
import { AuthModule } from "../src/auth";
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { AssertInbox } = require("./assertinbox.cjs");
const inbox = new AssertInbox({
key: process.env.ASSERTINBOX_KEY,
namespace: process.env.ASSERTINBOX_NAMESPACE,
});
describe("sign-up email (e2e)", () => {
let app: INestApplication;
let tag: string;
let email: string;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AuthModule] }).compile();
app = moduleRef.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
});
beforeEach(() => {
tag = inbox.uniqueTag("nest");
email = inbox.address(tag);
});
afterEach(async () => {
await inbox.delete(tag).catch(() => {});
});
it("emails a code that verifies the address", async () => {
await request(app.getHttpServer()).post("/auth/register").send({ email }).expect(202);
const code: string = await inbox.waitForOtp(tag, { retries: 2 });
expect(code).toMatch(/^[0-9]{6}$/);
await request(app.getHttpServer())
.post("/auth/verify")
.send({ email, code })
.expect(200)
.expect({ verified: true });
}, 90000);
it("rejects a wrong code", async () => {
await request(app.getHttpServer()).post("/auth/register").send({ email }).expect(202);
const code: string = await inbox.waitForOtp(tag, { retries: 2 });
const wrong = code === "000000" ? "111111" : "000000";
await request(app.getHttpServer()).post("/auth/verify").send({ email, code: wrong }).expect(400);
}, 90000);
});
Two choices keep the suite dependable. The second test waits for the real email even though it never uses the code to verify: waiting proves that this request sent mail, and it makes the test pick a wrong value that cannot equal the real one. And both tests share one application instance, built once in beforeAll, because booting Nest for every test is the slowest part of an e2e run.
Configure Jest and the environment
Nest's own template keeps e2e settings in test/jest-e2e.json. A minimal version for this guide is below. The long testTimeout is a ceiling, not a delay: a wait returns as soon as the email arrives.
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": { "^.+\\.(t|j)s$": "ts-jest" },
"testTimeout": 90000
}
Run it with the mailer settings of your staging provider, for example SMTP_HOST=smtp.example.com SMTP_USER=... SMTP_PASS=... MAIL_FROM=no-reply@yourdomain.example npx jest --config test/jest-e2e.json. Do not commit those values.
Run it in CI
Store ASSERTINBOX_KEY, ASSERTINBOX_NAMESPACE and the SMTP settings as secrets in your CI provider, and pass them as environment variables to the job that runs the e2e command. Never print them. Run the e2e job on its own so a slow mail provider does not hold up the fast unit tests, and use a staging sender account with a low daily quota rather than your production one.
Troubleshooting
Nest can't resolve dependencies of the AuthController. The module must list the providers, as inAuthModuleabove, andreflect-metadatamust be imported once; Nest's testing package does this for you.- The register call returns 500. The mailer threw. Check
SMTP_HOST, the port and theSMTP_SECUREflag: port 465 normally needstrue, ports 587 and 25 needfalse. Exceeded timeout of 5000 ms. The spec sets 90 seconds per test, but atestTimeoutin another config can win. Pass--config test/jest-e2e.json.request is not a function. The default-import form needsesModuleInterop. Otherwise writeimport * as request from "supertest".- HTTP 401 from AssertInbox. The key is missing or wrong in the environment that runs the tests.
- No email arrives. Look at your provider's activity log for the address. Some providers hold the first message to a new domain for a short time.
Related guides: Jest email verification test, Express and Nodemailer sign-up test.
Next steps
For unique tags, the trigger-then-wait order, retries and cleanup in one place, read Reliable email tests. More stacks are on the guides page.