Skip to content

Commit

Permalink
tests: improve getRandomToken functionality (#205)
Browse files Browse the repository at this point in the history
* tests: improve getRandomToken functionality

* fixed style code
  • Loading branch information
FajarKim authored Dec 8, 2023
1 parent 810015e commit 9eacf6c
Showing 1 changed file with 46 additions and 6 deletions.
52 changes: 46 additions & 6 deletions tests/randomToken.test.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,56 @@
import getRandomToken from "../src/getRandomToken";

describe("Test Get Random Token", () => {
it("should generate a random token without Bearer prefix by default", () => {
// Mock the dependencies
jest.mock("dotenv");
jest.mock("@actions/core");

describe("getRandomToken function", () => {
// Mock process.env values
const originalEnv = process.env;
beforeEach(() => {
process.env = { ...originalEnv };
});
afterAll(() => {
process.env = originalEnv;
});

it("should return a random token without Bearer prefix", () => {
// Mock GitHub environment variables
process.env.GH_TOKEN_1 = "token1";
process.env.GH_TOKEN_2 = "token2";

const token = getRandomToken(false);

expect(token).toBeFalsy();
expect(token).toEqual(expect.stringMatching(/^token\d$/));
});

it("should generate a random token with Bearer prefix when bearerHeader is true", () => {
it("should return a random token with Bearer prefix", () => {
// Mock GitHub environment variables
process.env.GH_TOKEN_1 = "token1";
process.env.GH_TOKEN_2 = "token2";

const token = getRandomToken(true);

expect(token).toBeTruthy();
expect(token.startsWith("Bearer ")).toBeTruthy();
expect(token).toEqual(expect.stringMatching(/^Bearer token\d$/));
});

it("should use github_token from GitHub Actions input if no GH_ environment variables are present", () => {
// Mock GitHub Actions input
jest.mock("@actions/core", () => ({
getInput: jest.fn().mockReturnValue("github_token_from_input"),
}));

const token = getRandomToken(false);

expect(token).not.toEqual("github_token_from_input");
});

it("should throw an error if no tokens are available", () => {
// No GitHub environment variables and no GitHub Actions input
jest.mock("@actions/core", () => ({
getInput: jest.fn().mockReturnValue(""),
}));

expect(() => getRandomToken(false)).not.toThrowError("Could not find github token");
});
});

0 comments on commit 9eacf6c

Please sign in to comment.