Replace jest.mock's with overriding dependencies (#6014)

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
Janne Savolainen authored and GitHub committed 2022-08-23 13:04:00 +03:00
1 parent 03d2389f01
commit 81f7bd3c2c
50 files changed
+788 -605

No files matched your search

@@ -4,28 +4,38 @@
*/
import React from "react";
import { render, waitFor } from "@testing-library/react";
import { waitFor } from "@testing-library/react";
import { ClusterLocalTerminalSetting } from "../cluster-local-terminal-settings";
import userEvent from "@testing-library/user-event";
import { stat } from "fs/promises";
import { Notifications } from "../../../notifications";
import type { Stats } from "fs";
import type { Cluster } from "../../../../../common/cluster/cluster";
const mockStat = stat as jest.MockedFunction<typeof stat>;
jest.mock("fs", () => {
const actual = jest.requireActual("fs");
actual.promises.stat = jest.fn();
return actual;
});
jest.mock("../../../notifications");
import { getDiForUnitTesting } from "../../../../getDiForUnitTesting";
import type { DiRender } from "../../../test-utils/renderFor";
import { renderFor } from "../../../test-utils/renderFor";
import showErrorNotificationInjectable from "../../../notifications/show-error-notification.injectable";
import statInjectable from "../../../../../common/fs/stat/stat.injectable";
describe("ClusterLocalTerminalSettings", () => {
let render: DiRender;
let showErrorNotificationMock: jest.Mock;
let statMock: jest.Mock;
beforeEach(() => {
const di = getDiForUnitTesting({ doGeneralOverrides: true });
showErrorNotificationMock = jest.fn();
statMock = jest.fn();
di.override(statInjectable, () => statMock);
di.override(
showErrorNotificationInjectable,
() => showErrorNotificationMock,
);
render = renderFor(di);
jest.resetAllMocks();
});
@@ -89,7 +99,7 @@ describe("ClusterLocalTerminalSettings", () => {
});
it("should save the new CWD if path is a directory", async () => {
mockStat.mockImplementation(async (path) => {
statMock.mockImplementation(async (path) => {
expect(path).toBe("/foobar");
return {
@@ -114,7 +124,7 @@ describe("ClusterLocalTerminalSettings", () => {
});
it("should not save the new CWD if path is a file", async () => {
mockStat.mockImplementation(async (path) => {
statMock.mockImplementation(async (path) => {
expect(path).toBe("/foobar");
return {
@@ -136,6 +146,6 @@ describe("ClusterLocalTerminalSettings", () => {
userEvent.type(dn, "/foobar");
userEvent.click(dom.baseElement);
await waitFor(() => expect(Notifications.error).toBeCalled());
await waitFor(() => expect(showErrorNotificationMock).toHaveBeenCalled());
});
});
@@ -8,79 +8,25 @@ import { observer } from "mobx-react";
import type { Cluster } from "../../../../common/cluster/cluster";
import { Input } from "../../input";
import { SubTitle } from "../../layout/sub-title";
import { stat } from "fs/promises";
import { Notifications } from "../../notifications";
import { isErrnoException, resolveTilde } from "../../../utils";
import type { ShowNotification } from "../../notifications";
import { resolveTilde } from "../../../utils";
import { Icon } from "../../icon";
import { PathPicker } from "../../path-picker";
import { isWindows } from "../../../../common/vars";
import type { Stats } from "fs";
import logger from "../../../../common/logger";
import { lowerFirst } from "lodash";
import { withInjectables } from "@ogre-tools/injectable-react";
import showErrorNotificationInjectable from "../../notifications/show-error-notification.injectable";
import type { ValidateDirectory } from "../../../../common/fs/validate-directory.injectable";
import validateDirectoryInjectable from "../../../../common/fs/validate-directory.injectable";
export interface ClusterLocalTerminalSettingProps {
cluster: Cluster;
}
function getUserReadableFileType(stats: Stats): string {
if (stats.isFile()) {
return "a file";
}
if (stats.isFIFO()) {
return "a pipe";
}
if (stats.isSocket()) {
return "a socket";
}
if (stats.isBlockDevice()) {
return "a block device";
}
if (stats.isCharacterDevice()) {
return "a character device";
}
return "an unknown file type";
interface Dependencies {
showErrorNotification: ShowNotification;
validateDirectory: ValidateDirectory;
}
/**
* Validate that `dir` currently points to a directory. If so return `false`.
* Otherwise, return a user readable error message string for displaying.
* @param dir The path to be validated
*/
async function validateDirectory(dir: string): Promise<string | false> {
try {
const stats = await stat(dir);
if (stats.isDirectory()) {
return false;
}
return `the provided path is ${getUserReadableFileType(stats)} and not a directory.`;
} catch (error) {
switch (isErrnoException(error) ? error.code : undefined) {
case "ENOENT":
return `the provided path does not exist.`;
case "EACCES":
return `search permissions is denied for one of the directories in the prefix of the provided path.`;
case "ELOOP":
return `the provided path is a sym-link which points to a chain of sym-links that is too long to resolve. Perhaps it is cyclic.`;
case "ENAMETOOLONG":
return `the pathname is too long to be used.`;
case "ENOTDIR":
return `a prefix of the provided path is not a directory.`;
default:
logger.warn(`[CLUSTER-LOCAL-TERMINAL-SETTINGS]: unexpected error in validateDirectory for resolved path=${dir}`, error);
return error ? lowerFirst(String(error)) : "of an unknown error, please try again.";
}
}
}
export const ClusterLocalTerminalSetting = observer(({ cluster }: ClusterLocalTerminalSettingProps) => {
const NonInjectedClusterLocalTerminalSetting = observer(({ cluster, showErrorNotification, validateDirectory }: Dependencies & ClusterLocalTerminalSettingProps) => {
if (!cluster) {
return null;
}
@@ -109,15 +55,15 @@ export const ClusterLocalTerminalSetting = observer(({ cluster }: ClusterLocalTe
cluster.preferences.terminalCWD = undefined;
} else {
const dir = resolveTilde(directory);
const errorMessage = await validateDirectory(dir);
const result = await validateDirectory(dir);
if (errorMessage) {
Notifications.error(
if (!result.callWasSuccessful) {
showErrorNotification(
<>
<b>Terminal Working Directory</b>
<p>
{"Your changes were not saved because "}
{errorMessage}
{result.error}
</p>
</>,
);
@@ -200,3 +146,16 @@ export const ClusterLocalTerminalSetting = observer(({ cluster }: ClusterLocalTe
</>
);
});
export const ClusterLocalTerminalSetting = withInjectables<Dependencies, ClusterLocalTerminalSettingProps>(
NonInjectedClusterLocalTerminalSetting,
{
getProps: (di, props) => ({
showErrorNotification: di.inject(showErrorNotificationInjectable),
validateDirectory: di.inject(validateDirectoryInjectable),
...props,
}),
},
);