Unable to invalidate the require cache / jest cache

Viewed 220

I am unable to invalidate the require cache / jest cache.

The second require gets the same file content even though it was changed.

This works as expected.

import { existsSync, unlinkSync, writeFileSync } from "fs";
import { resolve } from "path";

const logModules = () => {
  console.log(
    Object.keys(require.cache).filter((x) => x.indexOf("node_modules") === -1)
  );
};

const filePath = "/tmp/test.js";

// lets write a module
writeFileSync(filePath, "module.exports = 'test';");
console.log(existsSync(filePath)); // true
console.log(require(filePath)); // 'test'
unlinkSync(filePath); // true

logModules(); // tmp/test.js is there as expected
delete require.cache[resolve(filePath)];
logModules(); // tmp/test.js is gone

// lets write a different module but at the same file path a.k.a changing
writeFileSync(filePath, "module.exports = 'second test';");
console.log(existsSync(filePath)); // true
console.log(require(filePath)); // 'test second'
unlinkSync(filePath); // true

This doesn't work.

In my jest test, it's not working. The second test's require resolves to the same content.

const filePath = "/tmp/test.js";
describe("what?", () => {
  it("run 1", async () => {
    // lets write a module
    writeFileSync(filePath, "module.exports = 'test';");
    console.log(existsSync(filePath)); // true
    expect(require(filePath)).toBe("test"); // true
    unlinkSync(filePath); // true

    logModules(); // tmp/test.js is there as expected
    delete require.cache[resolve(filePath)];
    logModules(); // tmp/test.js is still there
    jest.resetModules();
    logModules(); // tmp/test.js is gone
  });

  it("run 2, fails", async () => {
    // lets write a different module but at the same file path a.k.a changing
    writeFileSync(filePath, "module.exports = 'second test';");
    console.log(existsSync(filePath)); // true
    expect(require(filePath)).toBe("second test"); // FAIL
    /*
    Expected: "second test"
    Received: "test"
    */
    unlinkSync(filePath);
  });
});

I read a lot and know that jest is special here.

I tried jest.resetModules() but with the same result.

0 Answers
Related