title: kill a looped task nicely from a jest test
body: <p>I have a worker method 'doSomeWork' that is called in a loop, based on a flag that will be changed if a signal to terminate is received.</p>
  <pre><code>let RUNNING = true;
  
  let pid;
  
  export function getPid() {
    return pid;
  }
  
  export async function doSomeWork() {
    console.log(&quot;Doing some work!&quot;);
  }
  
  export const run = async () =&gt; {
    console.log(&quot;starting run process with PID %s&quot;, process.pid);
    pid = process.pid;
    while (RUNNING) {
      await doSomeWork();
    }
    console.log(&quot;done&quot;);
  };
  run()
    .then(() =&gt; {
      console.log(&quot;finished&quot;);
    })
    .catch((e) =&gt; console.error(&quot;failed&quot;, e));
  
  process.on(&quot;SIGTERM&quot;, () =&gt; {
    RUNNING = false;
  });
  
  </code></pre>
  <p>I am happy with this and now need to write a test:  I want to</p>
  <ul>
  <li>trigger the loop</li>
  <li>inject a 'SIGTERM' to the src process</li>
  <li>give the loop a chance to finish nicely</li>
  <li>see 'finished' in the logs to know that the run method has been killed.</li>
  </ul>
  <p>here is my attempt (not working)  The test code all executes, but the src loop isn't killed.</p>
  <pre><code>import * as main from &quot;../src/program&quot;;
  
  describe(&quot;main&quot;, () =&gt; {
    it(&quot;a test&quot;, () =&gt; {
      main.run();
  
      setTimeout(function () {
        console.log(&quot;5 seconds have passed - killing now!&quot;);
        const mainProcessPid = main.getPid();
        process.kill(mainProcessPid, &quot;SIGTERM&quot;);
      }, 5000);
  
      setTimeout(function () {
        console.log(&quot;5 secs of tidy up time has passed&quot;);
      }, 5000);
    });
  });
  
  </code></pre>
  <p>I think the setTimeout isn't blocking the test thread, but I am not sure how to achieve this in node/TS.</p>
  <p>sandbox at <a href="https://codesandbox.io/s/exciting-voice-goncm" rel="nofollow noreferrer">https://codesandbox.io/s/exciting-voice-goncm</a></p>
  <p>update sandbox with correct environment: <a href="https://codesandbox.io/s/keen-bartik-ltjtx" rel="nofollow noreferrer">https://codesandbox.io/s/keen-bartik-ltjtx</a></p>
  <p>any help appreciated :-)</p>
  <p>--update---
  I now see that process.kill isn't doing what I thought it was - even when I pass in the PID.  will try creating a process as a child of the test process, so I can send a signal to it then.  <a href="https://medium.com/@NorbertdeLangen/communicating-between-nodejs-processes-4e68be42b917" rel="nofollow noreferrer">https://medium.com/@NorbertdeLangen/communicating-between-nodejs-processes-4e68be42b917</a></p>