Skip to content

Commit feea444

Browse files
authored
chore: find and use an available port in tests (#11043)
You can now run `pnpm dev [test-suite]` even if port 3000 is busy. I copied the error message as is from what nextjs shows.
1 parent 257cad7 commit feea444

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

test/dev.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,31 @@ if (args.o) {
6868
await open(`http://localhost:3000${adminRoute}`)
6969
}
7070

71+
const findOpenPort = (startPort: number): Promise<number> => {
72+
return new Promise((resolve, reject) => {
73+
const server = createServer()
74+
server.listen(startPort, () => {
75+
console.log(`✓ Running on port ${startPort}`)
76+
server.close(() => resolve(startPort))
77+
})
78+
server.on('error', () => {
79+
console.log(`⚠ Port ${startPort} is in use, trying ${startPort + 1} instead.`)
80+
findOpenPort(startPort + 1)
81+
.then(resolve)
82+
.catch(reject)
83+
})
84+
})
85+
}
86+
7187
const port = process.env.PORT ? Number(process.env.PORT) : 3000
7288

89+
const availablePort = await findOpenPort(port)
90+
7391
// @ts-expect-error the same as in test/helpers/initPayloadE2E.ts
7492
const app = nextImport({
7593
dev: true,
7694
hostname: 'localhost',
77-
port,
95+
port: availablePort,
7896
dir: rootDir,
7997
})
8098

@@ -88,7 +106,7 @@ void app.prepare().then(() => {
88106
createServer(async (req, res) => {
89107
const parsedUrl = parse(req.url || '', true)
90108
await handle(req, res, parsedUrl)
91-
}).listen(port, () => {
109+
}).listen(availablePort, () => {
92110
resolveServer()
93111
})
94112
})
@@ -97,8 +115,8 @@ await serverPromise
97115
process.env.PAYLOAD_DROP_DATABASE = process.env.PAYLOAD_DROP_DATABASE === 'false' ? 'false' : 'true'
98116

99117
// fetch the admin url to force a render
100-
void fetch(`http://localhost:${port}${adminRoute}`)
101-
void fetch(`http://localhost:${port}/api/access`)
118+
void fetch(`http://localhost:${availablePort}${adminRoute}`)
119+
void fetch(`http://localhost:${availablePort}/api/access`)
102120
// This ensures that the next-server process is killed when this process is killed and doesn't linger around.
103121
process.on('SIGINT', () => {
104122
if (child) {

0 commit comments

Comments
 (0)