Repository: nodejs/node
Pull request: test: deflake test-runner-watch-mode-kill-signal

While trying to deflake the tests I've refactored making them much clearer and more performant (since there are no longer `setTimeout` calls), as far as I can tell the flake is also gone :slightly_smiling_face: 

Results:
 - https://ci.nodejs.org/job/node-stress-single-test/586
 - https://ci.nodejs.org/job/node-stress-single-test/587

Ref: https://github.com/nodejs/reliability/issues/1250

<!--
Before submitting a pull request, please read:

- the CONTRIBUTING guide at https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md
- the commit message formatting guidelines at
  https://github.com/nodejs/node/blob/HEAD/doc/contributing/pull-requests.md#commit-message-guidelines

For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes.

If you believe this PR should be highlighted in the Node.js CHANGELOG
please add the `notable-change` label.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
-->


Changed files:
filename: test/parallel/test-runner-watch-mode-kill-signal.mjs
patch: @@ -1,6 +1,5 @@
 import * as common from '../common/index.mjs';
 import { describe, it, beforeEach } from 'node:test';
-import { once } from 'node:events';
 import assert from 'node:assert';
 import { spawn } from 'node:child_process';
 import { writeFileSync } from 'node:fs';
@@ -19,27 +18,10 @@ if (common.isAIX) {
 }
 
 const indexContents = `
-  const { setTimeout } = require("timers/promises");
-  (async () => {
-      // Wait a few milliseconds to make sure that the
-      // parent process has time to attach its listeners
-      await setTimeout(200);
-
-      process.on('SIGTERM', () => {
-          console.log('__SIGTERM received__');
-          process.exit(123);
-      });
-
-      process.on('SIGINT', () => {
-          console.log('__SIGINT received__');
-          process.exit(124);
-      });
-
-      console.log('ready!');
-
-      // Wait for a long time (just to keep the process alive)
-      await setTimeout(100_000_000);
-  })();
+  process.on('SIGTERM', () => { console.log('__SIGTERM received__'); process.exit(); });
+  process.on('SIGINT', () => { console.log('__SIGINT received__'); process.exit(); });
+  process.send('script ready');
+  setTimeout(() => {}, 100_000);
 `;
 
 let indexPath = '';
@@ -54,60 +36,82 @@ describe('test runner watch mode with --watch-kill-signal', () => {
   beforeEach(refresh);
 
   it('defaults to SIGTERM', async () => {
-    let currentRun = Promise.withResolvers();
-    const child = spawn(process.execPath, ['--watch', indexPath], {
-      cwd: tmpdir.path,
-    });
+    const child = spawn(
+      process.execPath,
+      ['--watch', indexPath],
+      {
+        cwd: tmpdir.path,
+        stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
+      }
+    );
 
     let stdout = '';
     child.stdout.on('data', (data) => {
-      stdout += data.toString();
-      currentRun.resolve();
+      stdout += `${data}`;
+      if (/__(SIGINT|SIGTERM) received__/.test(stdout)) {
+        child.kill();
+      }
     });
 
-    await currentRun.promise;
+    child.on('message', (msg) => {
+      if (msg === 'script ready') {
+        writeFileSync(indexPath, indexContents);
+      }
+    });
 
-    currentRun = Promise.withResolvers();
-    writeFileSync(indexPath, indexContents);
+    await new Promise((resolve) =>
+      child.on('exit', () => {
+        resolve();
+      })
+    );
 
-    await currentRun.promise;
-    child.kill();
-    const [exitCode] = await once(child, 'exit');
     assert.match(stdout, /__SIGTERM received__/);
-    assert.strictEqual(exitCode, 123);
+    assert.doesNotMatch(stdout, /__SIGINT received__/);
   });
 
   it('can be overridden (to SIGINT)', async () => {
-    let currentRun = Promise.withResolvers();
-    const child = spawn(process.execPath, ['--watch', '--watch-kill-signal', 'SIGINT', indexPath], {
-      cwd: tmpdir.path,
-    });
-    let stdout = '';
+    const child = spawn(
+      process.execPath,
+      ['--watch', '--watch-kill-signal', 'SIGINT', indexPath],
+      {
+        cwd: tmpdir.path,
+        stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
+      }
+    );
 
+    let stdout = '';
     child.stdout.on('data', (data) => {
-      stdout += data.toString();
-      if (stdout.includes('ready!')) {
-        currentRun.resolve();
+      stdout += `${data}`;
+      if (/__(SIGINT|SIGTERM) received__/.test(stdout)) {
+        child.kill();
       }
     });
 
-    await currentRun.promise;
+    child.on('message', (msg) => {
+      if (msg === 'script ready') {
+        writeFileSync(indexPath, indexContents);
+      }
+    });
 
-    currentRun = Promise.withResolvers();
-    writeFileSync(indexPath, indexContents);
+    await new Promise((resolve) =>
+      child.on('exit', () => {
+        resolve();
+      })
+    );
 
-    await currentRun.promise;
-    child.kill();
-    const [exitCode] = await once(child, 'exit');
     assert.match(stdout, /__SIGINT received__/);
-    assert.strictEqual(exitCode, 124);
+    assert.doesNotMatch(stdout, /__SIGTERM received__/);
   });
 
   it('errors if an invalid signal is provided', async () => {
     const currentRun = Promise.withResolvers();
-    const child = spawn(process.execPath, ['--watch', '--watch-kill-signal', 'invalid_signal', indexPath], {
-      cwd: tmpdir.path,
-    });
+    const child = spawn(
+      process.execPath,
+      ['--watch', '--watch-kill-signal', 'invalid_signal', indexPath],
+      {
+        cwd: tmpdir.path,
+      }
+    );
     let stdout = '';
 
     child.stderr.on('data', (data) => {
@@ -117,6 +121,11 @@ describe('test runner watch mode with --watch-kill-signal', () => {
 
     await currentRun.promise;
 
-    assert.match(stdout, new RegExp(/TypeError \[ERR_UNKNOWN_SIGNAL\]: Unknown signal: invalid_signal/));
+    assert.match(
+      stdout,
+      new RegExp(
+        /TypeError \[ERR_UNKNOWN_SIGNAL\]: Unknown signal: invalid_signal/
+      )
+    );
   });
 });