diff --git a/lib/core/src/server/dev-server.test.ts b/lib/core/src/server/dev-server.test.ts new file mode 100644 index 000000000000..7339fabe3d98 --- /dev/null +++ b/lib/core/src/server/dev-server.test.ts @@ -0,0 +1,23 @@ +import ip from 'ip'; +import { getServerAddresses } from './dev-server'; + +jest.mock('ip'); +const mockedIp = ip as jest.Mocked; + +describe('getServerAddresses', () => { + beforeEach(() => { + mockedIp.address.mockReturnValue('192.168.0.5'); + }); + + it('builds addresses with a specified host', () => { + const { address, networkAddress } = getServerAddresses(9009, '192.168.89.89', 'http'); + expect(address).toEqual('http://localhost:9009/'); + expect(networkAddress).toEqual('http://192.168.89.89:9009/'); + }); + + it('builds addresses with local IP when host is not specified', () => { + const { address, networkAddress } = getServerAddresses(9009, '', 'http'); + expect(address).toEqual('http://localhost:9009/'); + expect(networkAddress).toEqual('http://192.168.0.5:9009/'); + }); +}); diff --git a/lib/core/src/server/dev-server.ts b/lib/core/src/server/dev-server.ts index 2c94a817bd4c..536e32ccb2b2 100644 --- a/lib/core/src/server/dev-server.ts +++ b/lib/core/src/server/dev-server.ts @@ -356,6 +356,13 @@ const startPreview = async ({ return { previewStats, previewTotalTime: process.hrtime(startTime) }; }; +export function getServerAddresses(port: number, host: string, proto: string) { + return { + address: `${proto}://localhost:${port}/`, + networkAddress: `${proto}://${host || ip.address()}:${port}/`, + }; +} + export async function storybookDevServer(options: any) { const app = express(); const server = await getServer(app, options); @@ -385,8 +392,7 @@ export async function storybookDevServer(options: any) { const { port, host } = options; const proto = options.https ? 'https' : 'http'; - const address = `${proto}://${host || 'localhost'}:${port}/`; - const networkAddress = `${proto}://${ip.address()}:${port}/`; + const { address, networkAddress } = getServerAddresses(port, host, proto); await new Promise((resolve, reject) => { // FIXME: Following line doesn't match TypeScript signature at all 🤔 @@ -414,7 +420,7 @@ export async function storybookDevServer(options: any) { ]); // TODO #13083 Remove this when compiling the preview is fast enough - if (!options.ci) openInBrowser(address); + if (!options.ci) openInBrowser(networkAddress); return { ...previewResult, ...managerResult, address, networkAddress }; }