|
| 1 | +import * as net from 'net'; |
| 2 | + |
| 3 | +import { findClosestOpenPort } from '../server-http'; |
| 4 | + |
| 5 | +describe('server-http', () => { |
| 6 | + describe('findClosestOpenPort', () => { |
| 7 | + let testServer: net.Server; |
| 8 | + const TEST_HOST = '127.0.0.1'; |
| 9 | + const TEST_PORT = 9876; |
| 10 | + |
| 11 | + afterEach(async () => { |
| 12 | + if (testServer) { |
| 13 | + await new Promise<void>((resolve) => { |
| 14 | + testServer.close(() => resolve()); |
| 15 | + }); |
| 16 | + } |
| 17 | + }); |
| 18 | + |
| 19 | + it('should return the same port if it is available', async () => { |
| 20 | + const port = await findClosestOpenPort(TEST_HOST, TEST_PORT); |
| 21 | + expect(port).toBe(TEST_PORT); |
| 22 | + }); |
| 23 | + |
| 24 | + it('should find the next available port when strictPort is false', async () => { |
| 25 | + // Occupy the test port |
| 26 | + testServer = net.createServer(); |
| 27 | + await new Promise<void>((resolve) => { |
| 28 | + testServer.listen(TEST_PORT, TEST_HOST, () => resolve()); |
| 29 | + }); |
| 30 | + |
| 31 | + const port = await findClosestOpenPort(TEST_HOST, TEST_PORT, false); |
| 32 | + expect(port).toBe(TEST_PORT + 1); |
| 33 | + }); |
| 34 | + |
| 35 | + it('should find the next available port when strictPort is not provided (defaults to false)', async () => { |
| 36 | + // Occupy the test port |
| 37 | + testServer = net.createServer(); |
| 38 | + await new Promise<void>((resolve) => { |
| 39 | + testServer.listen(TEST_PORT, TEST_HOST, () => resolve()); |
| 40 | + }); |
| 41 | + |
| 42 | + const port = await findClosestOpenPort(TEST_HOST, TEST_PORT); |
| 43 | + expect(port).toBe(TEST_PORT + 1); |
| 44 | + }); |
| 45 | + |
| 46 | + it('should throw an error when port is taken and strictPort is true', async () => { |
| 47 | + // Occupy the test port |
| 48 | + testServer = net.createServer(); |
| 49 | + await new Promise<void>((resolve) => { |
| 50 | + testServer.listen(TEST_PORT, TEST_HOST, () => resolve()); |
| 51 | + }); |
| 52 | + |
| 53 | + await expect(findClosestOpenPort(TEST_HOST, TEST_PORT, true)).rejects.toThrow( |
| 54 | + `Port ${TEST_PORT} is already in use. Please specify a different port or set strictPort to false.`, |
| 55 | + ); |
| 56 | + }); |
| 57 | + |
| 58 | + it('should return the port when available and strictPort is true', async () => { |
| 59 | + const port = await findClosestOpenPort(TEST_HOST, TEST_PORT, true); |
| 60 | + expect(port).toBe(TEST_PORT); |
| 61 | + }); |
| 62 | + }); |
| 63 | +}); |
0 commit comments