diff --git a/packages/core/src/__tests__/get-current-branch.test.ts b/packages/core/src/__tests__/get-current-branch.test.ts new file mode 100644 index 000000000..e697b9d9c --- /dev/null +++ b/packages/core/src/__tests__/get-current-branch.test.ts @@ -0,0 +1,65 @@ +import { execSync } from "child_process"; +import { CiEnv } from "env-ci"; +import { getCurrentBranch } from "../auto"; + +jest.mock('child_process') + +describe('getCurrentBranch', () => { + + beforeEach(() => { + jest.clearAllMocks() + }) + + describe('when isPr', () => { + it('returns pr branch from env ci when valid', () => { + const env: Partial = { + isPr: true, + prBranch: 'my-pr-branch' + } + expect(getCurrentBranch(env)).toBe('my-pr-branch') + }); + + it('tries git command when PR is invalid', () => { + const env: Partial = { + isPr: true, + prBranch: 'undefined' + } + + getCurrentBranch(env); + + expect(execSync).toHaveBeenCalledWith("git symbolic-ref --short HEAD", { + encoding: "utf8", + stdio: "ignore", + }) + }); + }) + + describe('when not isPr', () => { + + it('returns pr branch from env ci when valid', () => { + const env: Partial = { + isPr: false, + prBranch: 'my-pr-branch', + branch: 'my-release-branch' + } + + expect(getCurrentBranch(env)).toBe('my-release-branch'); + + expect(execSync).not.toHaveBeenCalled() + }); + + it('tries git command when branch name is invalid', () => { + const env: Partial = { + isPr: false, + prBranch: 'my-pr-branch', + branch: undefined + } + getCurrentBranch(env); + + expect(execSync).toHaveBeenCalledWith("git symbolic-ref --short HEAD", { + encoding: "utf8", + stdio: "ignore", + }) + }); + }) +}) \ No newline at end of file diff --git a/packages/core/src/utils/get-current-branch.ts b/packages/core/src/utils/get-current-branch.ts index f944fc156..75f23c890 100644 --- a/packages/core/src/utils/get-current-branch.ts +++ b/packages/core/src/utils/get-current-branch.ts @@ -1,7 +1,7 @@ -import envCi from "env-ci"; +import envCi, { CiEnv } from "env-ci"; import { execSync } from "child_process"; -const env = envCi(); +const defaultCiEnvironment = envCi(); /** * Validates that the given branch name should be returned by environment context @@ -9,7 +9,7 @@ const env = envCi(); const isValidBranch = (branch: string | undefined) => typeof branch === "string" && branch !== "undefined" /** Get the current branch the git repo is set to */ -export function getCurrentBranch() { +export function getCurrentBranch(env: Partial = defaultCiEnvironment) { const isPR = "isPr" in env && env.isPr; let branch: string | undefined; // env-ci sets branch to target branch (ex: main) in some CI services.