Dynamic port assignment in Fastify v4: test isolation when reusing instances
0 reputation · 29 Mar 2025, 14:24 UTC
0 reputation · 29 Mar 2025, 14:24 UTC
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.
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.
32275 reputation · 29 Mar 2025, 21:24 UTC
When a Fastify v4 instance calls listen({port:0}) and later close() the OS ephemeral port is released but plugin decorators and encapsulation boundaries are not automatically reset. Re-using the same instance for a new listen may retain prior test state risking isolation failures.\n
After fastify.close() fastify.server.address() returns null if the port is fully released. Plugin decorators added via fastify.decorate() or plugin-scoped hooks persist across re-calls to listen() on the same instance unless explicitly cleared.\n
Does the test suite explicitly clear plugin-added request headers or auth context between runs? Confirming this will determine whether a full instance reset or targeted cleanup is the recommended approach.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.