A utility for Vitest to create isolated test directories
npm install vitest-testdirs --save-dev
// index.test.ts
import { readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { testdir } from "vitest-testdirs";
describe("testdir", () => {
it("isolated-test", async () => {
const path = await testdir({
"file1.txt": "Hello, World!",
"file2.txt": "Hello, Vitest!",
});
expect(path).toBeDefined();
expect(path).toContain(".vitest-testdirs/vitest-testdir-isolated-test");
const file = await readFile(`${path}/file1.txt`, "utf8");
expect(file).toBe("Hello, World!");
});
});
When you are using withMetadata
on a Windows filesystem, the permission is not set correctly on directories. This is not something that can be fixed, in this library as the issue is either coming from node or libuv.
It mostly happens on Directories. You can try out the following example to see the issue.
import { readFile, writeFile } from "node:fs/promises";
import { expect, it } from "vitest";
import { testdir, withMetadata } from "../src";
it("windows", async () => {
const path = await testdir({
"file.txt": withMetadata("Hello, World!", { mode: 0o444 }), // This works
"nested": withMetadata({
"file.txt": "Hello, World!",
}, { mode: 0o555 }), // This doesn't work.
});
try {
await writeFile(`${path}/file.txt`, "Hello, Vitest!");
// This should throw an error
} catch (err) {
console.log(err);
}
const content = await readFile(`${path}/file.txt`, "utf8");
expect(content).not.toBe("Hello, Vitest!");
expect(content).toBe("Hello, World!");
try {
await writeFile(`${path}/nested/file.txt`, "Hello, Vitest!");
// This should throw an error, but not on Windows
} catch (err) {
console.log(err);
}
const nestedContent = await readFile(`${path}/nested/file.txt`, "utf8");
// The content is now changed, but it should not be possible to write to the file
expect(nestedContent).not.toBe("Hello, Vitest!");
expect(nestedContent).toBe("Hello, World!");
});
Published under MIT License.