diff --git a/packages/wrangler/src/__tests__/run-in-tmp.ts b/packages/wrangler/src/__tests__/run-in-tmp.ts index 94a05d513a97..69f3582fbe3a 100644 --- a/packages/wrangler/src/__tests__/run-in-tmp.ts +++ b/packages/wrangler/src/__tests__/run-in-tmp.ts @@ -1,15 +1,25 @@ -import * as os from "node:os"; +import os from "node:os"; import * as path from "node:path"; import * as fs from "fs"; const originalCwd = process.cwd(); -export function runInTempDir() { +export function runInTempDir({ homedir }: { homedir?: string } = {}) { let tmpDir: string; beforeEach(() => { tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "wrangler-tests")); process.chdir(tmpDir); + if (homedir !== undefined) { + // Override where the home directory is so that we can write our own user config, + // without destroying the real thing. + fs.mkdirSync(homedir); + // Note it is very important that we use the "default" value from "node:os" (e.g. `import os from "node:os";`) + // rather than an alias to the module (e.g. `import * as os from "node:os";`). + // This is because the module gets transpiled so that the "method" `homedir()` gets converted to a + // getter that is not configurable (and so cannot be spied upon). + jest.spyOn(os, "homedir").mockReturnValue(homedir); + } }); afterEach(() => { diff --git a/packages/wrangler/src/__tests__/whoami.test.tsx b/packages/wrangler/src/__tests__/whoami.test.tsx index d085a6b917b5..60a2799adca1 100644 --- a/packages/wrangler/src/__tests__/whoami.test.tsx +++ b/packages/wrangler/src/__tests__/whoami.test.tsx @@ -13,15 +13,12 @@ const ORIGINAL_CF_API_TOKEN = process.env.CF_API_TOKEN; const ORIGINAL_CF_ACCOUNT_ID = process.env.CF_ACCOUNT_ID; describe("getUserInfo()", () => { - runInTempDir(); + runInTempDir({ homedir: "./home" }); beforeEach(() => { // Clear the environment variables, so we can control them in the tests delete process.env.CF_API_TOKEN; delete process.env.CF_ACCOUNT_ID; - // Override where the home directory is so that we can specify a user config - mkdirSync("./home"); - jest.spyOn(os, "homedir").mockReturnValue("./home"); }); afterEach(() => {