Skip to content

Commit

Permalink
test: move home directory mocking into the runInTempDir() helper
Browse files Browse the repository at this point in the history
Since we would only want to mock out the home directory when we are also
running in a tmp directory, it makes sense to combine these.
This also makes this behaviour available for other tests outside the
whoami.test.ts file.
  • Loading branch information
petebacondarwin committed Jan 26, 2022
1 parent 7477b52 commit f9059ca
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
14 changes: 12 additions & 2 deletions packages/wrangler/src/__tests__/run-in-tmp.ts
Original file line number Diff line number Diff line change
@@ -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(() => {
Expand Down
5 changes: 1 addition & 4 deletions packages/wrangler/src/__tests__/whoami.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down

0 comments on commit f9059ca

Please sign in to comment.