What happens in tests when the requested port is in use? What's verified?
What happens in tests when the requested port is in use? What's verified?
About sindresorhus/get-port · 2 messages · last activity 7/20/2026
When the requested port is in use, the tests verify that get-port falls back to finding an alternative available port instead of returning the unavailable one.
For example, in the test "first port in preferred ports array is unavailable" [test.js:L81-L95], a server is bound to the first desired port (9090), and then getPort() is called with that port in the preferred ports array. The test verifies that the function returns the second port (9091) instead:
const desiredPorts = [9090, 9091];
const server = net.createServer();
await promisify(server.listen.bind(server))(desiredPorts[0]);
const port = await getPort({
port: desiredPorts,
});
t.is(port, desiredPorts[1]);
Similarly, the test "all preferred ports in array are unavailable" [test.js:L97-L120] verifies that when all preferred ports are occupied, getPort() returns a random available port that is neither of the preferred ones:
t.is(typeof port, 'number');
t.true(port > 0 && port < 65_536);
t.not(port, desiredPorts[0]);
t.not(port, desiredPorts[1]);
There's also a test for a single unavailable preferred port [test.js:L35-L41] that verifies a different port is returned when the desired one is taken.
FOLLOW_UPS:
- How does the locking mechanism prevent race conditions?
- What's the difference between reserve true and false?
- Can you exclude specific ports from being returned?
Want to ask your own question?
Open chat for sindresorhus/get-portPublic Q&A. Generated by RepoPilot from the actual source of sindresorhus/get-port. AI answers can be incomplete or stale — verify before relying on them.