fix(server): allow listening on number 0 port (#4781)

This commit is contained in:
Amos Wong 2019-01-19 20:23:18 +08:00 committed by Pooya Parsa
parent 991da1acf4
commit 602cf12216
2 changed files with 30 additions and 1 deletions

View File

@ -225,7 +225,7 @@ export default class Server {
async listen(port, host, socket) {
// Create a new listener
const listener = new Listener({
port: port || this.options.server.port,
port: isNaN(parseInt(port)) ? this.options.server.port : port,
host: host || this.options.server.host,
socket: socket || this.options.server.socket,
https: this.options.server.https,

View File

@ -41,4 +41,33 @@ describe('server listen', () => {
await nuxt.close()
})
test('should skip the use of default port when listening on port 0', async () => {
// Stub process.env.PORT
const stubDetails = {
originalValue: process.env.PORT,
hasProperty: 'PORT' in process.env
}
const DEFAULT_PORT = '2999'
process.env.PORT = DEFAULT_PORT
// Setup test
const nuxt = new Nuxt({ ...config, dev: true })
const listen = () => nuxt.server.listen(0, 'localhost') // Use port 0 to let allow host to randomly assign a free PORT
const toString = (x = '') => `${x}`
// Nuxt server should not be listening on the DEFAULT_PORT
await listen()
expect(toString(nuxt.server.listeners[0].port)).not.toBe(DEFAULT_PORT)
// Reset stub for process.env.PORT
if (stubDetails.hasProperty) {
process.env.PORT = stubDetails.originalValue
} else {
delete process.env.PORT
}
// Finalize test
await nuxt.close()
})
})