diff --git a/packages/transport-websockets/src/listener.ts b/packages/transport-websockets/src/listener.ts index 25d18835b3..cbb4913a91 100644 --- a/packages/transport-websockets/src/listener.ts +++ b/packages/transport-websockets/src/listener.ts @@ -341,20 +341,20 @@ export class WebSocketListener extends TypedEventEmitter impleme } getAddrs (): Multiaddr[] { + if (this.listeningMultiaddr == null) { + throw new Error('Listener is not ready yet') + } + const address = this.server.address() if (address == null) { - throw new Error('Listener is not ready yet') + return [] } if (typeof address === 'string') { throw new Error('Wrong address type received - expected AddressInfo, got string - are you trying to listen on a unix socket?') } - if (this.listeningMultiaddr == null) { - throw new Error('Listener is not ready yet') - } - const options = this.listeningMultiaddr.toOptions() const multiaddrs: Multiaddr[] = [] diff --git a/packages/transport-websockets/test/node.ts b/packages/transport-websockets/test/node.ts index 6baae5a67d..82b255e2cc 100644 --- a/packages/transport-websockets/test/node.ts +++ b/packages/transport-websockets/test/node.ts @@ -73,6 +73,22 @@ describe('listen', () => { void listener.listen(ma) }) + it('should return an empty address list when `getAddrs` called before listening has finished', async () => { + listener = ws.createListener({ upgrader }) + + void listener.listen(ma) + + // call getAddrs before sockets have opened + expect(listener.getAddrs()).to.be.empty() + }) + + it('should throw when `.getAddrs` called before `.listen`', async () => { + listener = ws.createListener({ upgrader }) + + // call getAddrs before sockets have opened + expect(() => listener.getAddrs()).to.throw(/not ready/) + }) + it('should error on starting two listeners on same address', async () => { listener = ws.createListener({ upgrader }) const dumbServer = http.createServer()