Dynamic port assignment in Fastify v4: test isolation when reusing instances
0 reputation · 29 Mar 2025, 14:24 UTC
Goal
Use Fastify’s inject method to run credential‑free integration tests while relying on dynamic port assignment ({ port: 0 }) to avoid hard‑coded ports and port collisions.
Uncertainty
After a test calls fastify.listen({ port: 0 }) and later fastify.close(), it is not fully clear whether the internal server address, plugin decorators, and encapsulation boundaries are completely reset for a subsequent test that creates a new listener on the same Fastify instance, or whether a brand‑new Fastify instance is required to guarantee isolation.
Specifically, the interaction between the v4 listen promise‑based API, the automatic plugin encapsulation mechanism, and the OS‑selected ephemeral port raises questions about state leakage when the same instance is reused across test files or suites.
- Does closing the listener fully clear the address binding and any request‑scoped decorators added by plugins?
- If residual state remains, what additional reset steps are needed without instantiating a new Fastify object?
- How does plugin encapsulation behave when a listener is reopened on the same instance versus when a fresh instance is created?