Skip to content

Commit

Permalink
fix: testing around current branch logic
Browse files Browse the repository at this point in the history
  • Loading branch information
lshadler committed Oct 25, 2021
1 parent f1c3f4a commit d0c97b7
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 3 deletions.
65 changes: 65 additions & 0 deletions packages/core/src/__tests__/get-current-branch.test.ts
Original file line number Diff line number Diff line change
@@ -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<CiEnv> = {
isPr: true,
prBranch: 'my-pr-branch'
}
expect(getCurrentBranch(env)).toBe('my-pr-branch')
});

it('tries git command when PR is invalid', () => {
const env: Partial<CiEnv> = {
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<CiEnv> = {
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<CiEnv> = {
isPr: false,
prBranch: 'my-pr-branch',
branch: undefined
}
getCurrentBranch(env);

expect(execSync).toHaveBeenCalledWith("git symbolic-ref --short HEAD", {
encoding: "utf8",
stdio: "ignore",
})
});
})
})
6 changes: 3 additions & 3 deletions packages/core/src/utils/get-current-branch.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
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
*/
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<CiEnv> = 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.
Expand Down

0 comments on commit d0c97b7

Please sign in to comment.