diff --git a/packages/test-utils/src/server.ts b/packages/test-utils/src/server.ts index 372f9a23b7..6415b856c9 100644 --- a/packages/test-utils/src/server.ts +++ b/packages/test-utils/src/server.ts @@ -4,8 +4,9 @@ import { getRandomPort, waitForPort } from 'get-port-please' import { fetch as _fetch, $fetch as _$fetch, FetchOptions } from 'ohmyfetch' import { useTestContext } from './context' -export async function listen () { +export async function startServer () { const ctx = useTestContext() + await stopServer() const port = await getRandomPort() ctx.url = 'http://localhost:' + port ctx.serverProcess = execa('node', [ @@ -13,6 +14,7 @@ export async function listen () { resolve(ctx.nuxt.options.nitro.output.dir, 'server/index.mjs') ], { env: { + ...process.env, PORT: String(port), NODE_ENV: 'test' } @@ -20,6 +22,13 @@ export async function listen () { await waitForPort(port, { retries: 8 }) } +export async function stopServer () { + const ctx = useTestContext() + if (ctx.serverProcess) { + await ctx.serverProcess.kill() + } +} + export function fetch (path: string, options?: any) { return _fetch(url(path), options) } diff --git a/packages/test-utils/src/setup/index.ts b/packages/test-utils/src/setup/index.ts index addfafcfe0..5b33673c87 100644 --- a/packages/test-utils/src/setup/index.ts +++ b/packages/test-utils/src/setup/index.ts @@ -1,6 +1,6 @@ import { createTestContext, setTestContext } from '../context' import { loadFixture, buildFixture } from '../nuxt' -import { listen } from '../server' +import { startServer, stopServer } from '../server' import { createBrowser } from '../browser' import type { TestHooks, TestOptions } from '../types' import setupJest from './jest' @@ -24,7 +24,9 @@ export function createTest (options: Partial): TestHooks { const afterAll = async () => { if (ctx.serverProcess) { - ctx.serverProcess.kill() + setTestContext(ctx) + await stopServer() + setTestContext(undefined) } if (ctx.nuxt && ctx.nuxt.options.dev) { await ctx.nuxt.close() @@ -44,7 +46,7 @@ export function createTest (options: Partial): TestHooks { } if (ctx.options.server) { - await listen() + await startServer() } if (ctx.options.waitFor) {