@@ -10,26 +10,36 @@ const globalFetch = globalThis.fetch || _fetch
1010
1111export interface StartServerOptions {
1212 env ?: Record < string , unknown >
13+ /**
14+ * Overrides the consola log level for the server subprocess.
15+ * Defaults to `TestOptions.logLevel` (which itself defaults to `1`).
16+ */
17+ logLevel ?: number
1318}
1419
1520export async function startServer ( options : StartServerOptions = { } ) {
1621 const ctx = useTestContext ( )
1722 await stopServer ( )
23+ ctx . serverLogs = [ ]
1824 const host = '127.0.0.1'
1925 const port = ctx . options . port || ( await getRandomPort ( host ) )
2026 ctx . url = `http://${ host } :${ port } /`
27+ const capture = ctx . options . captureServerLogs !== false
28+ const stdio = capture ? 'pipe' : 'inherit'
29+ const logLevel = String ( options . logLevel ?? ctx . options . logLevel )
2130 if ( ctx . options . dev ) {
2231 ctx . serverProcess = x ( 'nuxi' , [ '_dev' ] , {
2332 throwOnError : true ,
2433 nodeOptions : {
2534 cwd : ctx . nuxt ! . options . rootDir ,
26- stdio : 'inherit' ,
35+ stdio,
2736 env : {
2837 ...process . env ,
2938 _PORT : String ( port ) , // Used by internal _dev command
3039 PORT : String ( port ) ,
3140 HOST : host ,
3241 NODE_ENV : 'development' ,
42+ CONSOLA_LEVEL : logLevel ,
3343 ...ctx . options . env ,
3444 ...options . env ,
3545 } ,
@@ -49,12 +59,13 @@ export async function startServer(options: StartServerOptions = {}) {
4959 {
5060 throwOnError : true ,
5161 nodeOptions : {
52- stdio : 'inherit' ,
62+ stdio,
5363 env : {
5464 ...process . env ,
5565 PORT : String ( port ) ,
5666 HOST : host ,
5767 NODE_ENV : 'test' ,
68+ CONSOLA_LEVEL : logLevel ,
5869 ...ctx . options . env ,
5970 ...options . env ,
6071 } ,
@@ -63,6 +74,14 @@ export async function startServer(options: StartServerOptions = {}) {
6374 )
6475 }
6576
77+ if ( capture ) {
78+ ; ( async ( ) => {
79+ for await ( const line of ctx . serverProcess ! ) {
80+ ctx . serverLogs . push ( line )
81+ }
82+ } ) ( ) . catch ( ( ) => { } )
83+ }
84+
6685 await waitForServer ( { host, port, dev : ctx . options . dev } )
6786}
6887
@@ -137,6 +156,23 @@ export async function stopServer() {
137156 }
138157}
139158
159+ /**
160+ * Returns the lines captured from the server subprocess's stdout/stderr since
161+ * the last `startServer()` call (or `clearServerLogs()`).
162+ * Only populated when `captureServerLogs` is `true` (the default).
163+ */
164+ export function getServerLogs ( ) : string [ ] {
165+ return useTestContext ( ) . serverLogs
166+ }
167+
168+ /**
169+ * Clears the captured server log lines. Useful between requests when you want
170+ * to assert only on the logs produced by a specific operation.
171+ */
172+ export function clearServerLogs ( ) : void {
173+ useTestContext ( ) . serverLogs = [ ]
174+ }
175+
140176export function fetch ( path : string , options ?: RequestInit ) {
141177 return globalFetch ( url ( path ) , options )
142178}
0 commit comments