Skip to content

Commit 917d008

Browse files
committed
feat: add getAvailablePort helper function
1 parent 3c1c484 commit 917d008

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

test/unit/helpers.test.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { promises as fs } from "fs"
2-
import { tmpdir, useEnv } from "../../test/utils/helpers"
2+
import { getAvailablePort, tmpdir, useEnv } from "../../test/utils/helpers"
33

44
/**
55
* This file is for testing test helpers (not core code).
@@ -39,3 +39,15 @@ describe("useEnv", () => {
3939
expect(process.env[envKey]).toEqual("test environment variable")
4040
})
4141
})
42+
43+
describe("getAvailablePort", () => {
44+
it("should return a valid port", async () => {
45+
const port = await getAvailablePort()
46+
expect(port).toBeGreaterThan(0)
47+
})
48+
it("should return different ports for different calls", async () => {
49+
const portOne = await getAvailablePort()
50+
const portTwo = await getAvailablePort()
51+
expect(portOne).not.toEqual(portTwo)
52+
})
53+
})

test/utils/helpers.ts

+21
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { promises as fs } from "fs"
22
import * as os from "os"
33
import * as path from "path"
4+
import * as net from "net"
45

56
/**
67
* Return a mock of @coder/logger.
@@ -61,3 +62,23 @@ export function useEnv(key: string): [(nextValue: string | undefined) => string
6162

6263
return [setValue, resetValue]
6364
}
65+
66+
/**
67+
* Helper function to get a random port.
68+
*
69+
* Source: https://github.com/sindresorhus/get-port/blob/main/index.js#L23-L33
70+
*/
71+
export const getAvailablePort = (options?: net.ListenOptions): Promise<number> =>
72+
new Promise((resolve, reject) => {
73+
const server = net.createServer()
74+
server.unref()
75+
server.on("error", reject)
76+
server.listen(options, () => {
77+
// NOTE@jsjoeio: not a huge fan of the type assertion
78+
// but it works for now.
79+
const { port } = server.address() as net.AddressInfo
80+
server.close(() => {
81+
resolve(port)
82+
})
83+
})
84+
})

0 commit comments

Comments
 (0)