diff --git a/lib/chromedriver.js b/lib/chromedriver.js index 139f7f9..ff1bf82 100644 --- a/lib/chromedriver.js +++ b/lib/chromedriver.js @@ -40,7 +40,7 @@ function start(args, returnPromise) { command = process.platform === "win32" ? "chromedriver.exe" : "chromedriver"; } let port = getPortFromArgs(args); - if (!port) { + if (port === undefined) { args.push("--port=9515"); port = 9515; } @@ -49,6 +49,9 @@ function start(args, returnPromise) { cp.stderr.pipe(process.stderr); defaultInstance = cp; if (!returnPromise) return cp; + // with --port=0 the OS assigns a random port we cannot know here, so there is + // nothing to poll; resolve as soon as the process is spawned. + if (port === 0) return Promise.resolve(cp); const pollInterval = 100; const timeout = 10000; return tcpPortUsed.waitUntilUsed(port, pollInterval, timeout).then(function () { diff --git a/tests/start.test.js b/tests/start.test.js new file mode 100644 index 0000000..7359001 --- /dev/null +++ b/tests/start.test.js @@ -0,0 +1,47 @@ +const child_process = require("node:child_process"); + +describe("start", () => { + /** @type {import('child_process').ChildProcess} */ + let fakeCp; + let spawnSpy; + beforeEach(() => { + fakeCp = /** @type {any} */ ({ + stdout: { pipe: jest.fn() }, + stderr: { pipe: jest.fn() }, + kill: jest.fn(), + }); + jest.resetModules(); + spawnSpy = jest.spyOn(child_process, "spawn").mockClear().mockReturnValue(fakeCp); + }); + afterAll(() => jest.restoreAllMocks()); + + it("uses the default port when none is passed", () => { + const { start } = require("../lib/chromedriver"); + const args = []; + start(args); + expect(args).toContain("--port=9515"); + expect(spawnSpy.mock.calls[0][1]).toContain("--port=9515"); + }); + + it("keeps --port=0 instead of overriding it with the default", () => { + const { start } = require("../lib/chromedriver"); + const args = ["--port=0"]; + start(args); + expect(args).not.toContain("--port=9515"); + expect(spawnSpy.mock.calls[0][1]).toEqual(["--port=0"]); + }); + + it("resolves immediately for --port=0 when a promise is requested", async () => { + const { start } = require("../lib/chromedriver"); + const cp = await start(["--port=0"], true); + expect(cp).toBe(fakeCp); + }); + + it("keeps an explicit port", () => { + const { start } = require("../lib/chromedriver"); + const args = ["--port=9222"]; + start(args); + expect(args).not.toContain("--port=9515"); + expect(spawnSpy.mock.calls[0][1]).toEqual(["--port=9222"]); + }); +});