vitest
vitest copied to clipboard
Mock fs
What do you mean by that?
https://peeky.netlify.app/
Just an idea from Peeky, not sure if we want it
This seems like the most appropriate issue to share my struggle with mocking fs. TL;DR I can mock it with inconsistent module name, but can't keep track of calls.
engines.ts
import { readFileSync } from "fs";
export const getEngines = () => {
return readFileSync("engines.ts");
};
mock.vispec.ts
import { expect, test, vi } from "vitest";
import { getEngines } from "../engines.js";
test("works", async () => {
// Arrange
vi.mock("node:fs", async () => {
return {
...(await vi.importActual<typeof import("node:fs")>("node:fs")),
readFileSync: vi.fn().mockReturnValue(`mocked value`),
};
});
const { readFileSync } = await import("node:fs");
console.log(readFileSync);
// Act
const result = getEngines();
// Assert
expect(result).toBe("mocked value"); // works
expect(readFileSync).toHaveBeenCalled(); // doesn't
});
As soon as I changed import { readFileSync } from "fs"; to import { readFileSync } from "node:fs"; in engines.ts - it started working.
But still, quite an interesting artifact that mocking was actually kinda working even with an inconsistent module name.
This is something I think a lot of teams could benefit from too @antfu and @sheremet-va. I can see it being really useful for CLIs, scripts, and server code.
Mocking fs is a fine option, but isn't as powerful/intuitive as a mocked file system.