2022-02-11 13:22:58 +00:00
|
|
|
import { resolve } from 'path'
|
|
|
|
import { execa } from 'execa'
|
2022-02-28 21:41:44 +00:00
|
|
|
import { getRandomPort, waitForPort } from 'get-port-please'
|
2022-02-11 13:22:58 +00:00
|
|
|
import { fetch as _fetch, $fetch as _$fetch, FetchOptions } from 'ohmyfetch'
|
|
|
|
import { useTestContext } from './context'
|
|
|
|
|
2022-03-17 21:17:54 +00:00
|
|
|
export async function startServer () {
|
2022-02-11 13:22:58 +00:00
|
|
|
const ctx = useTestContext()
|
2022-03-17 21:17:54 +00:00
|
|
|
await stopServer()
|
2022-02-28 21:41:44 +00:00
|
|
|
const port = await getRandomPort()
|
2022-02-11 13:22:58 +00:00
|
|
|
ctx.url = 'http://localhost:' + port
|
2022-02-25 20:14:53 +00:00
|
|
|
ctx.serverProcess = execa('node', [
|
2022-02-11 13:22:58 +00:00
|
|
|
// @ts-ignore
|
|
|
|
resolve(ctx.nuxt.options.nitro.output.dir, 'server/index.mjs')
|
|
|
|
], {
|
|
|
|
env: {
|
2022-03-17 21:17:54 +00:00
|
|
|
...process.env,
|
2022-02-11 13:22:58 +00:00
|
|
|
PORT: String(port),
|
|
|
|
NODE_ENV: 'test'
|
|
|
|
}
|
|
|
|
})
|
2022-02-28 21:41:44 +00:00
|
|
|
await waitForPort(port, { retries: 8 })
|
2022-02-11 13:22:58 +00:00
|
|
|
}
|
|
|
|
|
2022-03-17 21:17:54 +00:00
|
|
|
export async function stopServer () {
|
|
|
|
const ctx = useTestContext()
|
|
|
|
if (ctx.serverProcess) {
|
|
|
|
await ctx.serverProcess.kill()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-11 13:22:58 +00:00
|
|
|
export function fetch (path: string, options?: any) {
|
|
|
|
return _fetch(url(path), options)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function $fetch (path: string, options?: FetchOptions) {
|
|
|
|
return _$fetch(url(path), options)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function url (path: string) {
|
|
|
|
const ctx = useTestContext()
|
|
|
|
if (!ctx.url) {
|
|
|
|
throw new Error('url is not availabe (is server option enabled?)')
|
|
|
|
}
|
|
|
|
return ctx.url + path
|
|
|
|
}
|