In the original project, there is a class that performs long-running tasks in separate processes on servers. These processes occasionally receive 'SIGINT' signals to stop, and I need to persist the state when this happens. To achieve this, I wrapped the work in an 'setInterval(,0)' function to allow the event loop to capture interrupts, as it wouldn't work within a 'while(true)' loop.
Now, I want to test if the Subject class works correctly - specifically by validating input. You can find a Minimal Working Example (MWE) here.
The work is implemented in 'subject.class.ts':
import { writeFileSync } from "fs";
import { tmpdir } from "os";
import { join, basename } from "path";
export default class Subject {
private counter = 0;
public doWork(inputdata: string): void {
if (!inputdata) {
process.exit(100); // exit if no input was given
}
setInterval(() => {
this.counter++;
if (this.counter > 10e2) {
process.exit(0);
}
if (this.counter % 10e1 === 0) {
console.log(this.counter);
}
}, 0);
}
public persist(): void {
const data = JSON.stringify(this.counter);
const path = join(tmpdir(), basename(__filename));
writeFileSync(path, data);
console.log(`Persisted to ${path}`);
}
}
To start the work, I create a new Subject instance, set interrupt handlers, and call the 'subj.doWork("peanut")' method in 'main.ts':
import Subject from "./subject.class";
const subj = new Subject();
process.on("exit", (exitcode: number) => {
if (exitcode === 0) {
process.stdout.write(`\nDone Success. :)\n`);
} else {
process.stderr.write(`\nDone with code: ${exitcode}\n`);
}
subj.persist();
process.stdout.write("exiting.");
process.exit(exitcode);
});
process.on("SIGINT", (signal: "SIGINT") => {
process.stdout.write(`\ncaught ${signal}`);
process.exit(13);
});
subj.doWork("peanut");
Everything functions correctly. However, when testing the call to 'process.exit', Jest exits before 'done' is called in the first 'it' block. Jest then displays error messages about attempted log writes. When unskipping the second case, the first one passes because Jest is still active. But the 'expect.toEqual(0);' statement is never executed, causing the test to succeed regardless of the value used. How can I properly test the Subject's work method?