How to Mock `fs.promises.writeFile` with Jest

I am trying to mock the promise version of fs.writeFile using Jest, and the mocked function is not being called.

Function to be tested (createFile.js):

const { writeFile } = require("fs").promises;

const createNewFile = async () => {
    await writeFile(`${__dirname}/newFile.txt`, "Test content");

module.exports = {

Jest Test (createFile.test.js):

const fs = require("fs").promises;
const { createNewFile } = require("./createFile.js");

it("Calls writeFile", async () => {
    const writeFileSpy = jest.spyOn(fs, "writeFile");

    await createNewFile();


I know that writeFile is actually being called because I ran node -e "require(\"./createFile.js\").createNewFile()" and the file was created.

Dependency Versions

  • Node.js: 14.1.0
  • Jest: 26.6.3

Read more here:

Content Attribution

This content was originally published by Dan Levy at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: