raszi / node-tmp

Temporary file and directory creator for node.js
MIT License
732 stars 93 forks source link

Why does tmp.setGracefulCleanup() not work within jest tests? #273

Closed rzacherl closed 1 year ago

rzacherl commented 2 years ago

Operating System

NodeJS Version

Tmp Version

0.2.1

Expected Behavior

Files created inside a jest test via tmp.fileSync() should get deleted automatically after the test ends (as it happens within the normal code)

Experienced Behavior

Files are still existing after jest test finished

rzacherl commented 2 years ago

Here's a short TypeScript code example:

import { writeFileSync } from "fs";
import tmp from "tmp";

tmp.setGracefulCleanup();

describe("tmp", () => {
  it("tmp", () => {
    const tempFile = tmp.fileSync();
    console.log(tempFile.name);
    writeFileSync(tempFile.name, "foo", "utf8");
  });
});
cmdcolin commented 2 years ago

I ran into this also and was curious what was going on, and I believe it also doesn't work in another context I use it (oclif)

silkentrance commented 2 years ago

ATM I do not have the time to look into this further. Since we have working tests for mocha, I presume that the problem lies with jest. Maybe I find some time in the upcoming weekend.

silkentrance commented 1 year ago

@rzacherl It has been a while... Sorry, my bad.

In the past, jest would use sandboxes and not necessarily terminate the process. So tmp graceful cleanup will not run until all tests have been run and the jest process exits.

If you need to have these files removed early, then you need to call the removeCallback at the end of your test.

graceful cleanup is more for the lazy developer who expects tmp to clean up everything on process exist.

silkentrance commented 1 year ago

Graceful cleanup only happens on process exit and not in-between test cases.

You need to manually call the remove callback in order to remove these files in-between tests.