Files
core/test/app.test.ts
T
chrnx 7c2454fe43
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 18s
CI / runtimes (deno) (pull_request) Successful in 33s
fix(app): an empty mountpoint mounts at the root again (GitHub #31)
GitHub #32 (merged from contrib) made `createApp` fail with a message
naming the module when its `@Module` metadata has no `mountpoint`,
instead of a TypeError from `joinPath`. The check tested falsiness, so
it also refused `mountpoint: ''`, which the type allows and which has
always mounted at the root (`joinPath('', '/hi')` is `/hi`).

Test for `typeof … !== 'string'` instead: a missing or non-string
mountpoint still fails with the new message, and `''` boots as before.
The CHANGELOG entry for #31 that #32 did not add is included.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 15:52:50 -05:00

773 lines
25 KiB
TypeScript

import 'reflect-metadata';
import { describe, expect, it, test, vi } from 'vitest';
import { Provider, Step, Route, Get, Post, Module, Transformer, getModuleMeta } from '../src/metadata';
import { JsonTransformer } from '../src/transformers';
import { Unauthorized } from '../src/signals';
import { createApp } from '../src/app';
import { needs, param, query, body } from '../src/params';
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } };
}
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Auth {
run(ctx: any) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('bad token');
return { user };
}
}
@Route('/users')
class UserCtl {
@Get('/:id')
@Transformer(JsonTransformer)
getUser(@needs('user') user: any, @param('id') id: string) {
return { id, user };
}
}
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [UserCtl] })
class ApiModule {}
test('inspect lists the ordered chain with origins', () => {
const app = createApp({ modules: [ApiModule] });
const lines = app.inspect('/api/users/:id');
expect(lines.map((l) => `${l.kind}:${l.name}`)).toEqual(['provider:db', 'step:user', 'handler:getUser']);
});
test('runtime module metadata without mountpoint names module and missing field', () => {
@Route('/broken')
class BrokenCtl {
@Get('/')
get() {
return { ok: true };
}
}
@Module({ mountpoint: '/broken', controllers: [BrokenCtl] })
class BrokenModule {}
const metadata = getModuleMeta(BrokenModule);
if (!metadata) throw new Error('test setup failed');
Object.defineProperty(metadata, 'mountpoint', { value: undefined });
expect(() => createApp({ modules: [BrokenModule] })).toThrow(/BrokenModule.*mountpoint/);
});
test("an empty mountpoint still mounts at the root, as it did before the missing-mountpoint check", async () => {
@Route('/')
class RootCtl {
@Get('/hi')
hi() {
return { ok: true };
}
}
@Module({ mountpoint: '', controllers: [RootCtl] })
class RootModule {}
const res = await createApp({ modules: [RootModule] }).fetch(new Request('http://x/hi'));
expect(res.status).toBe(200);
});
test('ready() is a no-op on a non-mesh app, so one protocol works for both', async () => {
// The point: code holding an `App` should not have to know whether it is a mesh app.
// `await app.ready(); app.graph()` is uniform — here it changes nothing and boots nothing.
const app = createApp({ modules: [ApiModule] });
const booted: string[] = [];
app.bus.on('boot:provider:start', (p) => booted.push(p.name));
const before = app.graph().nodes.length;
await app.ready();
expect(app.graph().nodes.length).toBe(before);
expect(booted).toEqual([]);
});
test('a logger plugin observes step:enter without mutating the chain', async () => {
const seen: string[] = [];
const logger = {
name: 'step-logger',
mount: (api: any) => api.bus.on('request:step:enter', (p: any) => seen.push(p.name)),
};
const app = createApp({ modules: [ApiModule], plugins: [logger] });
const server = await app.listen(0);
const port = (server.address() as any).port;
const ok = await fetch(`http://127.0.0.1:${port}/api/users/7`, { headers: { 'x-token': 'good' } });
expect(ok.status).toBe(200);
expect(await ok.json()).toEqual({ id: '7', user: { id: 'u1' } });
expect(seen).toContain('user');
const bad = await fetch(`http://127.0.0.1:${port}/api/users/7`, { headers: { 'x-token': 'nope' } });
expect(bad.status).toBe(401);
server.close();
});
test('required provider failure aborts boot', () => {
@Provider({ provides: 'broken' })
class Broken {
provide() {
throw new Error('cannot connect');
}
}
@Module({ mountpoint: '/x', providers: [Broken], steps: [], controllers: [] })
class BrokenModule {}
const app = createApp({ modules: [BrokenModule] });
return expect(app.listen(0)).rejects.toThrow(/provider 'broken' failed/);
});
test('optional provider failure warns but does not abort boot', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
@Provider({ provides: 'cache', optional: true })
class FlakyCache {
provide() {
throw new Error('cache down');
}
}
@Route('/ping')
class PingCtl {
@Get('/') ping() {
return { ok: true };
}
}
@Module({ mountpoint: '/sys', providers: [FlakyCache], steps: [], controllers: [PingCtl] })
class SysModule {}
const app = createApp({ modules: [SysModule] });
expect(app.degraded()).toEqual([]); // nothing degraded until boot runs
const server = await app.listen(0); // must NOT throw
expect(warn).toHaveBeenCalledWith(expect.stringContaining("optional provider 'cache' failed"));
// boot ends with a summary of everything running degraded, and it is queryable on the app
expect(warn).toHaveBeenCalledWith(expect.stringContaining('started with 1 degraded optional provider(s): cache'));
expect(app.degraded()).toEqual(['cache']);
server.close();
warn.mockRestore();
});
test('handler receives @query value through a live request', async () => {
@Route('/search')
class SearchCtl {
@Get('/')
run(@query('q') q: string) {
return { q };
}
}
@Module({ mountpoint: '/s', providers: [], steps: [], controllers: [SearchCtl] })
class SearchModule {}
const app = createApp({ modules: [SearchModule] });
const server = await app.listen(0);
const port = (server.address() as any).port;
const res = await fetch(`http://127.0.0.1:${port}/s/search/?q=hello`);
expect(await res.json()).toEqual({ q: 'hello' });
server.close();
});
test('boot fails when a handler needs something nothing provides', () => {
@Route('/things')
class ThingCtl {
@Get('/')
list(@needs('missing') _m: any) {
return [];
}
}
@Module({ mountpoint: '/t', providers: [], steps: [], controllers: [ThingCtl] })
class ThingModule {}
expect(() => createApp({ modules: [ThingModule] })).toThrow(/handler 'list' needs 'missing'/);
});
it('boot error for a misspelled @needs suggests the closest token', () => {
@Step({ provides: 'user', needs: [] })
class Auth {
run() {
return { user: 1 };
}
}
@Route('/u')
class Ctl {
@Get('/x') x(@needs('usr') u: any) {
return { u };
}
}
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/did you mean 'user'\?/);
});
import { Sse, Ws } from '../src/metadata';
import { inbound } from '../src/params';
import { channel } from '../src/channel';
describe('app streaming wiring', () => {
it('serves an SSE route declared with @Sse', async () => {
@Route('/')
class Ctl {
@Sse('/ticks') ticks() {
return (async function* () {
yield { t: 1 };
yield { t: 2 };
})();
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const addr = server.address() as import('net').AddressInfo;
const res = await fetch(`http://127.0.0.1:${addr.port}/ticks`, { headers: { accept: 'text/event-stream' } });
expect(res.headers.get('content-type')).toBe('text/event-stream');
const text = await res.text();
expect(text).toContain('data: {"t":1}');
server.close();
});
it('serves a @Ws route receiving @inbound and returning a channel', async () => {
@Route('/')
class Ctl {
@Ws('/echo') echo(@inbound() inc: AsyncIterable<string>) {
const out = channel<string>();
(async () => {
for await (const m of inc) out.push(`re:${m}`);
out.close();
})();
return out;
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const addr = server.address() as import('net').AddressInfo;
const WebSocket = (await import('ws')).default;
const client = new WebSocket(`ws://127.0.0.1:${addr.port}/echo`);
await new Promise((r) => client.on('open', r));
const got = new Promise<string>((r) => client.on('message', (d: Buffer) => r(d.toString())));
client.send('yo');
expect(await got).toBe('re:yo');
client.close();
server.close();
});
});
describe('per-route subgraph slicing', () => {
it('a route that does not @needs a step does not run it', async () => {
const ran: string[] = [];
@Step({ provides: 'tracked', needs: [] })
class Tracked {
run() {
ran.push('tracked');
return { tracked: true };
}
}
@Route('/')
class Ctl {
@Get('/needs') needs(@needs('tracked') t: any) {
return { t };
}
@Get('/free') free() {
return { ok: true };
}
}
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const port = (server.address() as any).port;
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
expect(ran).toEqual([]); // step did NOT run for /free
await fetch(`http://127.0.0.1:${port}/needs`).then((r) => r.json());
expect(ran).toEqual(['tracked']); // step ran for /needs
expect(app.inspect('/free').map((l) => l.kind)).toEqual(['handler']); // no step in the chain
server.close();
});
it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => {
// NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add.
const ran: string[] = [];
const observer = {
name: 'side-effect-observer',
mount: (api: any) =>
api.scope.add({
kind: 'step',
name: 'obs',
needs: [],
provides: [],
run: () => {
ran.push('obs');
return {};
},
}),
};
@Route('/')
class Ctl {
@Get('/free') free() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
const server = await app.listen(0);
const port = (server.address() as any).port;
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing
server.close();
});
it('an always-run observer step receives its declared needs even when the route does not need them', async () => {
let seen: any;
const observer = {
name: 'audit-observer',
mount: (api: any) =>
api.scope.add({
kind: 'step',
name: 'audit',
needs: ['user'],
provides: [],
run: (ctx: any) => {
seen = ctx.user;
return {};
},
}),
};
@Step({ provides: 'user', needs: [] })
class Auth {
run() {
return { user: { id: 'u1' } };
}
}
@Route('/')
class Ctl {
@Get('/free') free() {
return { ok: true };
}
} // does NOT @needs('user')
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
const server = await app.listen(0);
const port = (server.address() as any).port;
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined
server.close();
});
});
import { Rooms } from '../src/rooms';
import { toMermaid as renderMermaid } from '../src/graph-viz';
describe('app.graph / explain', () => {
it('graph() returns nodes (with origin/needs/provides) and routes with their sliced chain', async () => {
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: 1 };
}
}
@Step({ provides: 'user', needs: ['db'] })
class Auth {
run() {
return { user: 1 };
}
}
@Route('/u')
class Ctl {
@Get('/:id') get(@needs('user') u: any) {
return { u };
}
}
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const g = app.graph();
expect(g.nodes.find((n) => n.name === 'db')).toMatchObject({ kind: 'provider', origin: 'module:M' });
expect(g.nodes.find((n) => n.name === 'user')).toMatchObject({ kind: 'step', needs: ['db'] });
const route = g.routes.find((r) => r.pattern === '/api/u/:id')!;
expect(route.chain).toEqual(['db', 'user', 'get']);
expect(app.toMermaid()).toContain('flowchart');
});
it('explain() returns the rich chain with origin and a handler entry', async () => {
@Step({ provides: 'user', needs: [] })
class Auth {
run() {
return { user: 1 };
}
}
@Route('/u')
class Ctl {
@Get('/me') me(@needs('user') u: any) {
return { u };
}
}
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const e = app.explain('/api/u/me');
expect(e).toMatchObject({ pattern: '/api/u/me', method: 'GET', transport: 'buffer' });
expect(e.chain.map((c) => `${c.kind}:${c.name}`)).toEqual(['step:user', 'handler:me']);
expect(e.chain[0]).toMatchObject({ origin: 'module:M', provides: ['user'] });
});
});
describe('devGraph endpoint', () => {
const portOf = (s: any) => (s.address() as any).port;
it('serves /__graph__ as HTML when devGraph:true', async () => {
@Route('/u')
class Ctl {
@Get('/me') me() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], devGraph: true });
const s = await app.listen(0);
const html = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`).then((r) => r.text());
expect(html).toContain('cytoscape');
expect(html).toContain('/api/u/me');
const mmd = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`, { headers: { accept: 'text/plain' } });
expect(mmd.headers.get('content-type')).toContain('text/plain');
expect(await mmd.text()).toContain('flowchart');
s.close();
});
it('does NOT mount /__graph__ without devGraph', async () => {
@Route('/u')
class Ctl {
@Get('/me') me() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const s = await app.listen(0);
const res = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`);
expect(res.status).toBe(404);
s.close();
});
it('serves /__graph__ and /__openapi__ over app.fetch too (runtime-agnostic dev tools)', async () => {
@Route('/u')
class Ctl {
@Get('/me') me() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], devGraph: true, devOpenapi: true });
const graph = await app.fetch(new Request('http://x/__graph__'));
expect(graph.status).toBe(200);
expect(await graph.text()).toContain('cytoscape');
const openapi = await app.fetch(new Request('http://x/__openapi__'));
expect(openapi.status).toBe(200);
expect(((await openapi.json()) as { openapi: string }).openapi).toBe('3.1.0');
// still absent when the flags are off, on the fetch path too
const off = createApp({ modules: [M] });
expect((await off.fetch(new Request('http://x/__graph__'))).status).toBe(404);
});
});
describe('graceful shutdown', () => {
// A module whose only route never responds, so shutdown always has something in flight to give
// up on — the deadline is the only thing that can end close().
const hangModule = () => {
@Route('/')
class Ctl {
@Get('/hang') hang() {
return new Promise(() => {});
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
return M;
};
const listenHanging = async (app: ReturnType<typeof createApp>): Promise<number> => {
const server = await app.listen(0);
const port = (server.address() as any).port;
fetch(`http://127.0.0.1:${port}/hang`).catch(() => {});
await new Promise((r) => setTimeout(r, 50)); // let the request reach the handler
return port;
};
it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
@Route('/')
class Ctl {
@Sse('/ticks') ticks() {
return (async function* () {
yield { t: 1 };
await new Promise((r) => setTimeout(r, 1000));
yield { t: 2 };
})();
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const port = (server.address() as any).port;
const res = await fetch(`http://127.0.0.1:${port}/ticks`, { headers: { accept: 'text/event-stream' } });
const reader = res.body!.getReader();
await reader.read(); // first event; stream still open
await app.close(); // must NOT hang despite the open stream
await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow();
reader.cancel().catch(() => {});
});
it('close({ timeoutMs }) forces shutdown when a handler never responds', async () => {
@Route('/')
class Ctl {
@Get('/hang') hang() {
return new Promise(() => {}); // never resolves — simulates a stuck handler
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const port = (server.address() as any).port;
fetch(`http://127.0.0.1:${port}/hang`).catch(() => {});
await new Promise((r) => setTimeout(r, 50));
const start = Date.now();
await app.close({ timeoutMs: 300 });
expect(Date.now() - start).toBeLessThan(600);
});
// The app-level default exists for the case where close() is reached from a signal handler or a
// test helper nobody local owns, so it has to work with close() called bare.
it('createApp({ shutdownTimeoutMs }) applies when close() is called with no options', async () => {
const app = createApp({ modules: [hangModule()], shutdownTimeoutMs: 300 });
await listenHanging(app);
const start = Date.now();
await app.close();
expect(Date.now() - start).toBeLessThan(600);
});
// The interesting half of the precedence rule: an app-level default long enough to fail this
// test if it won, so the assertion can only pass if the per-call value took priority.
it('close({ timeoutMs }) overrides the app-level default', async () => {
const app = createApp({ modules: [hangModule()], shutdownTimeoutMs: 30_000 });
await listenHanging(app);
const start = Date.now();
await app.close({ timeoutMs: 300 });
expect(Date.now() - start).toBeLessThan(600);
});
});
describe('overrides', () => {
const portOf = (s: any) => (s.address() as any).port;
it('overrides a provider token with a plain value (wrapped as a merge object)', async () => {
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: { real: true } };
}
}
@Route('/u')
class Ctl {
@Get('/x') x(@needs('db') db: any) {
return { db };
}
}
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], overrides: { db: { fake: true } } });
const s = await app.listen(0);
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: { fake: true } });
s.close();
});
it('overrides with a function runner', async () => {
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: 'real' };
}
}
@Route('/u')
class Ctl {
@Get('/x') x(@needs('db') db: any) {
return { db };
}
}
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], overrides: { db: () => ({ db: 'fn' }) } });
const s = await app.listen(0);
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: 'fn' });
s.close();
});
it('rejects an override for an unknown token', async () => {
@Route('/u')
class Ctl {
@Get('/x') x() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], overrides: { nope: 1 } });
await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
});
});
describe('rooms auto-provide', () => {
it('injects a built-in rooms instance resolvable via @needs("rooms")', async () => {
@Route('/r')
class Ctl {
@Get('/x') x(@needs('rooms') rooms: Rooms) {
return { ok: rooms instanceof Rooms };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const s = await app.listen(0);
const port = (s.address() as any).port;
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
s.close();
});
// This used to be allowed, and the user's provider silently replaced the framework's. The same
// held for `logger`, where every `@needs('logger')` in the app then got something that was not
// the logger core writes to — a divergence discovered from a log line that never appeared.
// Framework token names are reserved now, and taking one is a boot error.
it('refuses a user-declared rooms provider instead of silently replacing the built-in', () => {
@Provider({ provides: 'rooms' })
class MyRooms {
provide() {
return { rooms: { custom: true } };
}
}
@Route('/r')
class Ctl {
@Get('/x') x(@needs('rooms') rooms: any) {
return rooms;
}
}
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/'rooms' is reserved by the framework/);
});
});
test('per-route maxBodyBytes overrides the server default', async () => {
@Route('/up')
class C {
@Post('/small', { maxBodyBytes: 10 }) small(@body() _b: unknown) {
return { ok: true };
}
@Post('/big') big(@body() _b: unknown) {
return { ok: true };
}
}
@Module({ mountpoint: '/', providers: [], steps: [], controllers: [C] })
class M {}
const app = createApp({ modules: [M], limits: { maxBodyBytes: 1000 } });
const server = await app.listen(0);
const port = (server.address() as any).port;
const payload = JSON.stringify({ x: 'aaaaaaaaaaaaaaaaaaaa' }); // ~30 bytes, over the route's 10-byte cap
const opts = { method: 'POST', headers: { 'content-type': 'application/json' }, body: payload };
const tight = await fetch(`http://127.0.0.1:${port}/up/small`, opts);
expect(tight.status).toBe(413); // per-route cap of 10 bytes
const loose = await fetch(`http://127.0.0.1:${port}/up/big`, opts);
expect(loose.status).toBe(200); // falls back to the server's 1000-byte limit
server.close();
});
describe('route table validation', () => {
it('rejects routes with the same method and effective pattern', () => {
@Route('/users')
class DuplicateCtl {
@Get('/:id') byId() {
return {};
}
@Get('/:name') byName() {
return {};
}
}
@Module({ mountpoint: '/api', controllers: [DuplicateCtl] })
class DuplicateModule {}
expect(() => createApp({ modules: [DuplicateModule] })).toThrow(
/ambiguous route GET.*\/api\/users\/:name.*DuplicateCtl\.byName.*DuplicateCtl\.byId/,
);
});
it('allows the same effective pattern under different methods', () => {
@Route('/users')
class MethodsCtl {
@Get('/:id') get() {
return {};
}
@Post('/:name') post() {
return {};
}
}
@Module({ mountpoint: '/api', controllers: [MethodsCtl] })
class MethodsModule {}
expect(() => createApp({ modules: [MethodsModule] })).not.toThrow();
});
});
describe('listen() on a port already taken (#138)', () => {
@Route('/')
class TakenCtl {
@Get('/') get() {
return 'ok';
}
}
@Module({ mountpoint: '/', controllers: [TakenCtl] })
class TakenModule {}
it('rejects with EADDRINUSE, and the app can still close or listen elsewhere', async () => {
const { createServer } = await import('node:net');
const blocker = createServer();
await new Promise<void>((resolve) => blocker.listen(0, resolve));
const app = createApp({ modules: [TakenModule] });
try {
await expect(app.listen((blocker.address() as { port: number }).port)).rejects.toMatchObject({
code: 'EADDRINUSE',
});
const server = await app.listen(0);
const res = await fetch(`http://127.0.0.1:${(server.address() as { port: number }).port}/`);
expect(res.status).toBe(200);
} finally {
await app.close();
blocker.close();
}
});
it('close() after a failed listen resolves', async () => {
const { createServer } = await import('node:net');
const blocker = createServer();
await new Promise<void>((resolve) => blocker.listen(0, resolve));
const app = createApp({ modules: [TakenModule] });
await expect(app.listen((blocker.address() as { port: number }).port)).rejects.toThrow();
await app.close();
blocker.close();
});
});