Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const config: Config = {
],
watchPathIgnorePatterns: ["<rootDir>/.testing/", "<rootDir>/testing/"],
collectCoverageFrom: ["lib/**/*.{js,jsx,ts,tsx}"],
restoreMocks: true,
Copy link
Contributor Author

@marla-hoggard marla-hoggard Apr 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general, I still have calls in each test file for this, but you can set this here to automatically restore. Seemed like a nice catch-all in case we forget somewhere.

https://jestjs.io/docs/configuration#restoremocks-boolean

};

export default config;
2 changes: 1 addition & 1 deletion lib/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { pull } from "./commands/pull";
import { quit } from "./utils/quit";
import { version } from "../../package.json";
import logger from "./utils/logger";
import { initAPIToken } from "./services/apiToken";
import initAPIToken from "./services/apiToken/initAPIToken";
import { initProjectConfig } from "./services/projectConfig";
import appContext from "./utils/appContext";

Expand Down
27 changes: 0 additions & 27 deletions lib/src/services/apiToken.test.ts

This file was deleted.

149 changes: 0 additions & 149 deletions lib/src/services/apiToken.ts

This file was deleted.

105 changes: 105 additions & 0 deletions lib/src/services/apiToken/collectAndSaveToken.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import * as CollectToken from "./collectToken";
import * as GetURLHostname from "./getURLHostname";
import * as configService from "../globalConfig";
import appContext from "../../utils/appContext";
import * as utils from "../../utils/quit";
import collectAndSaveToken from "./collectAndSaveToken";

describe("collectAndSaveToken", () => {
let priorToken: string | undefined;
let priorHost: string;

let collectTokenSpy: jest.SpiedFunction<typeof CollectToken.default>;
let getURLHostnameSpy: jest.SpiedFunction<typeof GetURLHostname.default>;
let saveTokenSpy: jest.SpiedFunction<typeof configService.saveToken>;
let quitSpy: jest.SpiedFunction<typeof utils.quit>;

const token = "token";
const host = "host";
const apiHost = "apiHost";
const sanitizedHost = "hostname";

beforeEach(() => {
priorToken = appContext.apiToken;
priorHost = appContext.apiHost;
appContext.setApiToken("");
appContext.apiHost = apiHost;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the functions that use appContext values that we want to specify, i'm saving the original value, changing it to what we want, then restoring the prior value after the test. This might be total overkill, but it seemed like a nice safety measure. Thoughts?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is fine for now.

collectTokenSpy = jest.spyOn(CollectToken, "default");
getURLHostnameSpy = jest
.spyOn(GetURLHostname, "default")
.mockReturnValue(sanitizedHost);
saveTokenSpy = jest
.spyOn(configService, "saveToken")
.mockImplementation(() => Promise.resolve());
quitSpy = jest
.spyOn(utils, "quit")
.mockImplementation(() => Promise.resolve());
});

afterEach(() => {
appContext.setApiToken(priorToken);
appContext.apiHost = priorHost;
jest.restoreAllMocks();
});

it("collects, saves and returns a token", async () => {
collectTokenSpy.mockResolvedValue(token);

expect(appContext.apiToken).toBe("");
const result = await collectAndSaveToken();

expect(collectTokenSpy).toHaveBeenCalled();
expect(getURLHostnameSpy).toHaveBeenCalledWith(appContext.apiHost);
expect(saveTokenSpy).toHaveBeenCalledWith(
appContext.configFile,
sanitizedHost,
token
);
expect(result).toBe(token);
expect(appContext.apiToken).toBe(token);
});

it("uses the host if provided", async () => {
collectTokenSpy.mockResolvedValue(token);

expect(appContext.apiToken).toBe("");

const result = await collectAndSaveToken(host);
expect(collectTokenSpy).toHaveBeenCalled();
expect(getURLHostnameSpy).toHaveBeenCalledWith(host);
expect(saveTokenSpy).toHaveBeenCalledWith(
appContext.configFile,
sanitizedHost,
token
);
expect(result).toBe(token);
});

it("handles empty string error", async () => {
collectTokenSpy.mockImplementation(() => Promise.reject(""));

expect(appContext.apiToken).toBe("");
const response = await collectAndSaveToken();

expect(collectTokenSpy).toHaveBeenCalled();
expect(quitSpy).toHaveBeenCalledWith("", 0);
expect(appContext.apiToken).toBe("");
expect(response).toBe("");
expect(getURLHostnameSpy).not.toHaveBeenCalled();
expect(saveTokenSpy).not.toHaveBeenCalled();
});

it("handles other errors", async () => {
collectTokenSpy.mockImplementation(() => Promise.reject("some error"));

expect(appContext.apiToken).toBe("");
const response = await collectAndSaveToken();

expect(collectTokenSpy).toHaveBeenCalled();
expect(quitSpy).toHaveBeenCalledWith(expect.stringContaining("Error ID:"));
expect(appContext.apiToken).toBe("");
expect(response).toBe("");
expect(getURLHostnameSpy).not.toHaveBeenCalled();
expect(saveTokenSpy).not.toHaveBeenCalled();
});
});
46 changes: 46 additions & 0 deletions lib/src/services/apiToken/collectAndSaveToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import appContext from "../../utils/appContext";
import * as configService from "../globalConfig";
import logger from "../../utils/logger";
import { quit } from "../../utils/quit";
import * as Sentry from "@sentry/node";
import collectToken from "./collectToken";
import getURLHostname from "./getURLHostname";

/**
* Collects a token from the user and saves it to the global config file
* @param host The host to save the token for
* @returns The collected token
*/
export default async function collectAndSaveToken(
host: string = appContext.apiHost
) {
try {
const token = await collectToken();
logger.writeLine(
`Thanks for authenticating. We'll save the key to: ${logger.info(
appContext.configFile
)}\n`
);
const sanitizedHost = getURLHostname(host);
configService.saveToken(appContext.configFile, sanitizedHost, token);
appContext.setApiToken(token);
return token;
} catch (error) {
// https://github.com/enquirer/enquirer/issues/225#issue-516043136
// Empty string corresponds to the user hitting Ctrl + C
if (error === "") {
await quit("", 0);
return "";
}

const eventId = Sentry.captureException(error);
const eventStr = `\n\nError ID: ${logger.info(eventId)}`;

await quit(
logger.errorText(
"Something went wrong. Please contact support or try again later."
) + eventStr
);
return "";
}
}
36 changes: 36 additions & 0 deletions lib/src/services/apiToken/collectToken.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import collectToken from "./collectToken";
import * as PromptForApiToken from "./promptForApiToken";
import logger from "../../utils/logger";

describe("collectToken", () => {
let promptForApiTokenSpy: jest.SpiedFunction<
typeof PromptForApiToken.default
>;

const token = "token";

beforeEach(() => {
logger.url = jest.fn((msg: string) => msg);
logger.bold = jest.fn((msg: string) => msg);
logger.info = jest.fn((msg: string) => msg);
logger.writeLine = jest.fn((msg: string) => {});

promptForApiTokenSpy = jest
.spyOn(PromptForApiToken, "default")
.mockResolvedValue({ token });
});

afterEach(() => {
jest.restoreAllMocks();
});

it("prompts for API token and returns it", async () => {
const response = await collectToken();
expect(response).toBe(token);
expect(logger.url).toHaveBeenCalled();
expect(logger.bold).toHaveBeenCalled();
expect(logger.info).toHaveBeenCalled();
expect(logger.writeLine).toHaveBeenCalled();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this overkill? Should i ditch the logger checks? Does it make the test too brittle/resistent to change?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's okay to be brittle here as this will rarely change, and it does help us know that the messages were logged out. if the messages weren't getting logged out, that would be useful to know.

expect(promptForApiTokenSpy).toHaveBeenCalled();
});
});
Loading