vitest icon indicating copy to clipboard operation
vitest copied to clipboard

Mock fs

Open antfu opened this issue 3 years ago • 4 comments
trafficstars

antfu avatar Dec 13 '21 07:12 antfu

What do you mean by that?

sheremet-va avatar Dec 20 '21 05:12 sheremet-va

image https://peeky.netlify.app/

Just an idea from Peeky, not sure if we want it

antfu avatar Dec 20 '21 06:12 antfu

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.

Maxim-Mazurok avatar Jun 27 '22 10:06 Maxim-Mazurok

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.

mrmckeb avatar May 30 '23 02:05 mrmckeb