Mocking "fs" with Bun's test/mock

141 Views Asked by At

I'm trying to mock fs using Bun's Jest compatible inbuilt test/mocking framework as described here:

https://bun.sh/docs/test/mocks

Following the example gives me code that looks like this:

import { expect, test, mock } from "bun:test";
import fs from "fs";

mock.module("fs", () => {
    console.log("Mocking")
    return {
        mkdirSync: (path: string) => { 
            console.log("mkdirSync", path);
            return "mocked";
        }
    };
});
console.log("Mocked fs")

test("Mkdir", async () => {
    const dir = fs.mkdirSync("mock-dir", { recursive: true });
    expect(dir).toBe("mocked");
});

The real function is still getting called though, not the mock, i.e. the test fails. What am I missing?

1

There are 1 best solutions below

0
dubaniewicz On

This just happened to me...

You need to move the mock.module("fs"... into a separate file and use --preload

See this link: https://bun.sh/docs/test/mocks#hoisting-preloading