@@ -8,19 +8,34 @@ const scripts = {
88 child : path . join ( __dirname , 'fixtures' , 'child.js' ) ,
99} ;
1010
11+ // Helper to poll for a condition on process tree
12+ async function waitForCondition (
13+ pid : number ,
14+ condition : ( children : any [ ] ) => boolean ,
15+ maxWaitMs = 3000 ,
16+ ) : Promise < any [ ] > {
17+ const startTime = Date . now ( ) ;
18+ while ( Date . now ( ) - startTime < maxWaitMs ) {
19+ const children = await psTree ( pid ) ;
20+ if ( condition ( children ) ) {
21+ return children ;
22+ }
23+ await new Promise ( ( resolve ) => setTimeout ( resolve , 100 ) ) ;
24+ }
25+ return psTree ( pid ) ; // Final attempt
26+ }
27+
1128describe ( 'psTree()' , ( ) => {
1229 test ( 'Spawn a Parent process which has Ten Child Processes' , async ( ) => {
1330 const parent = exec ( `node ${ scripts . parent } ` ) ;
1431
15- // Wait for the child process(es) to spawn.
16- await new Promise ( ( resolve ) => setTimeout ( resolve , 500 ) ) ;
17-
18- const children = await psTree ( parent . pid ! ) ;
32+ // Poll until child processes are detected
33+ const children = await waitForCondition ( parent . pid ! , ( c ) => c . length > 0 ) ;
1934
2035 expect ( children . length ) . toBeGreaterThan ( 0 ) ;
2136
22- // Allow time for the processes to be terminated.
23- await new Promise ( ( resolve ) => setTimeout ( resolve , 2000 ) ) ;
37+ // Poll until processes terminate
38+ await waitForCondition ( parent . pid ! , ( c ) => c . length === 0 , 10000 ) ;
2439
2540 const postKillChildren = await psTree ( parent . pid ! ) ;
2641
@@ -30,17 +45,17 @@ describe('psTree()', () => {
3045 test ( 'Includes itself if includeRoot is true' , async ( ) => {
3146 const parent = exec ( `node ${ scripts . parent } ` ) ;
3247
33- // Wait for the child process(es) to spawn.
34- await new Promise ( ( resolve ) => setTimeout ( resolve , 500 ) ) ;
35-
36- const processes = await psTree ( parent . pid ! , true ) ;
48+ // Poll until processes are detected (parent + at least one child)
49+ await waitForCondition ( parent . pid ! , ( c ) => c . length > 1 , 3000 ) ;
3750
38- const parentProcess = processes . find ( ( process ) => Number . parseInt ( process . PID , 10 ) === parent . pid ! ) ;
51+ // Get processes with includeRoot after waiting
52+ const processesWithRoot = await psTree ( parent . pid ! , true ) ;
53+ const parentProcess = processesWithRoot . find ( ( process ) => Number . parseInt ( process . PID , 10 ) === parent . pid ! ) ;
3954
4055 expect ( parentProcess ) . toBeDefined ( ) ;
4156
42- // Allow time for the processes to be terminated.
43- await new Promise ( ( resolve ) => setTimeout ( resolve , 2000 ) ) ;
57+ // Poll until processes terminate
58+ await waitForCondition ( parent . pid ! , ( c ) => c . length === 0 , 10000 ) ;
4459
4560 const postKillChildren = await psTree ( parent . pid ! ) ;
4661
0 commit comments