Skip to content

Commit

Permalink
test: Remove loglevel mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
Ninfa-Jeon committed Feb 5, 2025
1 parent 5da598a commit 46b2aca
Show file tree
Hide file tree
Showing 38 changed files with 69 additions and 414 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
"fuse.js": "7.0.0",
"lodash.isequal": "4.5.0",
"lodash.mergewith": "4.6.2",
"loglevel": "^1.9.2",
"loglevel": "1.9.2",
"prism-react-renderer": "2.4.1",
"prismjs": "1.29.0",
"react": "18.3.1",
Expand Down
13 changes: 0 additions & 13 deletions src/components/App/App.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { render, screen } from "@testing-library/react";
import log from "loglevel";
import * as reactGA from "react-ga";
import { Provider } from "react-redux";
import configureStore from "redux-mock-store";
Expand Down Expand Up @@ -27,21 +26,9 @@ vi.mock("react-router", async () => {
};
});

vi.mock("loglevel", async () => {
const actual = await vi.importActual("loglevel");
return {
...actual,
error: vi.fn(),
};
});

const mockStore = configureStore([]);

describe("App", () => {
beforeEach(() => {
vi.spyOn(log, "error").mockImplementation(() => vi.fn());
});

afterEach(() => {
vi.resetAllMocks();
vi.unstubAllEnvs();
Expand Down
46 changes: 0 additions & 46 deletions src/components/LogIn/UserPassForm/UserPassForm.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import log from "loglevel";
import { vi } from "vitest";

import { thunks as appThunks } from "store/app";
Expand All @@ -10,27 +9,9 @@ import { generalStateFactory } from "testing/factories/general";
import { rootStateFactory } from "testing/factories/root";
import { renderComponent } from "testing/utils";

import { Label } from "../types";

import UserPassForm from "./UserPassForm";

vi.mock("loglevel", async () => {
const actual = await vi.importActual("loglevel");
return {
...actual,
error: vi.fn(),
};
});

describe("UserPassForm", () => {
beforeEach(() => {
vi.spyOn(log, "error").mockImplementation(() => vi.fn());
});

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

it("should log in", async () => {
// Mock the result of the thunk to be a normal action so that it can be tested
// for. This is necessary because we don't have a full store set up which
Expand Down Expand Up @@ -70,31 +51,4 @@ describe("UserPassForm", () => {
type: "connectAndStartPolling",
});
});

it("should display console error when trying to log in", async () => {
vi.spyOn(appThunks, "connectAndStartPolling").mockImplementation(
vi.fn().mockReturnValue({ type: "connectAndStartPolling" }),
);
vi.spyOn(dashboardStore, "useAppDispatch").mockImplementation(
vi
.fn()
.mockReturnValue((action: unknown) =>
action instanceof Object &&
"type" in action &&
action.type === "connectAndStartPolling"
? Promise.reject(
new Error("Error while dispatching connectAndStartPolling!"),
)
: null,
),
);

renderComponent(<UserPassForm />);
await userEvent.click(screen.getByRole("button"));
expect(appThunks.connectAndStartPolling).toHaveBeenCalledTimes(1);
expect(log.error).toHaveBeenCalledWith(
Label.POLLING_ERROR,
new Error("Error while dispatching connectAndStartPolling!"),
);
});
});
4 changes: 2 additions & 2 deletions src/components/LogIn/UserPassForm/UserPassForm.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { unwrapResult } from "@reduxjs/toolkit";
import log from "loglevel";
import type { FormEvent } from "react";

import bakery from "juju/bakery";
import { thunks as appThunks } from "store/app";
import { actions as generalActions } from "store/general";
import { getWSControllerURL } from "store/general/selectors";
import { useAppDispatch, useAppSelector } from "store/store";
import { logger } from "utils/logger";

import { Label } from "../types";

Expand Down Expand Up @@ -36,7 +36,7 @@ const UserPassForm = () => {
if (bakery) {
dispatch(appThunks.connectAndStartPolling())
.then(unwrapResult)
.catch((error) => log.error(Label.POLLING_ERROR, error));
.catch((error) => logger.error(Label.POLLING_ERROR, error));
}
}

Expand Down
33 changes: 0 additions & 33 deletions src/components/ShareCard/ShareCard.test.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,11 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import log from "loglevel";
import { vi } from "vitest";

import ShareCard from "./ShareCard";
import { Label } from "./types";

vi.mock("loglevel", async () => {
const actual = await vi.importActual("loglevel");
return {
...actual,
error: vi.fn(),
};
});

describe("Share Card", () => {
beforeEach(() => {
vi.spyOn(log, "error").mockImplementation(() => vi.fn());
});

it("should display appropriate text", () => {
render(
<ShareCard
Expand Down Expand Up @@ -86,24 +73,4 @@ describe("Share Card", () => {
await userEvent.selectOptions(screen.getByRole("combobox"), "write");
expect(accessSelectChangeFn).toHaveBeenCalled();
});

it("should log error when trying to change access", async () => {
const removeUserFn = vi.fn();
const accessSelectChangeFn = vi.fn(() => Promise.reject(new Error()));
render(
<ShareCard
userName="janedoe"
lastConnected="2021-06-03T16:03:15Z"
access="read"
isOwner={false}
removeUser={removeUserFn}
accessSelectChange={accessSelectChangeFn}
/>,
);
await userEvent.selectOptions(screen.getByRole("combobox"), "write");
expect(log.error).toHaveBeenCalledWith(
Label.ACCESS_CHANGE_ERROR,
new Error(),
);
});
});
4 changes: 2 additions & 2 deletions src/components/ShareCard/ShareCard.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type { ErrorResults } from "@canonical/jujulib/dist/api/facades/model-manager/ModelManagerV9";
import { Button, Select } from "@canonical/react-components";
import log from "loglevel";
import { useEffect, useState } from "react";

import SlideDownFadeOut from "animations/SlideDownFadeOut";
import TruncatedTooltip from "components/TruncatedTooltip";
import { formatFriendlyDateToNow } from "components/utils";
import { logger } from "utils/logger";

import "./_share-card.scss";
import { Label } from "./types";
Expand Down Expand Up @@ -118,7 +118,7 @@ export default function ShareCard({
return;
})
.catch((error) =>
log.error(Label.ACCESS_CHANGE_ERROR, error),
logger.error(Label.ACCESS_CHANGE_ERROR, error),
);
}}
value={access}
Expand Down
19 changes: 0 additions & 19 deletions src/hooks/useLocalStorage.test.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,8 @@
import { act, renderHook } from "@testing-library/react";
import log from "loglevel";
import { vi } from "vitest";

import useLocalStorage from "./useLocalStorage";

vi.mock("loglevel", async () => {
const actual = await vi.importActual("loglevel");
return {
...actual,
error: vi.fn(),
};
});

describe("useLocalStorage", () => {
beforeEach(() => {
vi.spyOn(log, "error").mockImplementation(() => vi.fn());
});

afterEach(() => {
localStorage.clear();
});
Expand All @@ -43,10 +29,6 @@ describe("useLocalStorage", () => {
const { result } = renderHook(() =>
useLocalStorage("test-key", "init-val"),
);
expect(log.error).toHaveBeenCalledWith(
"Unable to parse local storage:",
expect.any(Error),
);
const [value] = result.current;
expect(value).toBe("init-val");
});
Expand Down Expand Up @@ -76,7 +58,6 @@ describe("useLocalStorage", () => {
act(() => {
setValue(circular as unknown as string);
});
expect(log.error).toHaveBeenCalledWith(expect.any(Error));
const [value] = result.current;
expect(value).toBe("init-val");
expect(JSON.parse(localStorage.getItem("test-key") ?? "")).toBe("init-val");
Expand Down
7 changes: 4 additions & 3 deletions src/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import log from "loglevel";
import { useState } from "react";

import { logger } from "utils/logger";

function useLocalStorage<V>(
key: string,
initialValue: V,
Expand All @@ -13,7 +14,7 @@ function useLocalStorage<V>(
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// Not shown in UI. Logged for debugging purposes.
log.error("Unable to parse local storage:", error);
logger.error("Unable to parse local storage:", error);
return initialValue;
}
});
Expand All @@ -27,7 +28,7 @@ function useLocalStorage<V>(
window.localStorage.setItem(key, stringified);
} catch (error) {
// Not shown in UI. Logged for debugging purposes.
log.error(error);
logger.error(error);
}
};

Expand Down
13 changes: 0 additions & 13 deletions src/hooks/useLogout.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import log from "loglevel";
import { vi } from "vitest";

import { Label } from "hooks/useLogout";
Expand All @@ -10,19 +9,7 @@ import { renderComponent, renderWrappedHook } from "testing/utils";

import useLogout from "./useLogout";

vi.mock("loglevel", async () => {
const actual = await vi.importActual("loglevel");
return {
...actual,
error: vi.fn(),
};
});

describe("useLogout", () => {
beforeEach(() => {
vi.spyOn(log, "error").mockImplementation(() => vi.fn());
});

it("should logout", async () => {
vi.spyOn(appThunks, "logOut").mockImplementation(
vi.fn().mockReturnValue({ type: "logOut", catch: vi.fn() }),
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useLogout.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Button } from "@canonical/react-components";
import { unwrapResult } from "@reduxjs/toolkit";
import log from "loglevel";
import reactHotToast from "react-hot-toast";

import ToastCard from "components/ToastCard";
import { thunks as appThunks } from "store/app";
import { useAppDispatch } from "store/store";
import { logger } from "utils/logger";

export enum Label {
LOGOUT_ERROR = "Error when trying to logout.",
Expand All @@ -31,7 +31,7 @@ const useLogout = () => {
</>
</ToastCard>
));
log.error(Label.LOGOUT_ERROR, error);
logger.error(Label.LOGOUT_ERROR, error);
});
};
};
Expand Down
46 changes: 0 additions & 46 deletions src/index.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { screen, waitFor } from "@testing-library/dom";
import log from "loglevel";
import type { UnknownAction } from "redux";
import { vi } from "vitest";

import * as storeModule from "store";
Expand Down Expand Up @@ -34,14 +32,6 @@ vi.mock("store", () => {
};
});

vi.mock("loglevel", async () => {
const actual = await vi.importActual("loglevel");
return {
...actual,
error: vi.fn(),
};
});

const appVersion = packageJSON.version;

describe("renderApp", () => {
Expand All @@ -54,8 +44,6 @@ describe("renderApp", () => {
enumerable: true,
value: new URL(window.location.href),
});
// Hide the config errors from the test output.
vi.spyOn(log, "error").mockImplementation(() => vi.fn());
rootNode = document.createElement("div");
rootNode.setAttribute("id", ROOT_ID);
document.body.appendChild(rootNode);
Expand Down Expand Up @@ -257,10 +245,6 @@ describe("renderApp", () => {
});

describe("getControllerAPIEndpointErrors", () => {
beforeEach(() => {
vi.spyOn(log, "error").mockImplementation(() => vi.fn());
});

it("should handle secure protocol", () => {
expect(
getControllerAPIEndpointErrors("wss://example.com:80/api"),
Expand Down Expand Up @@ -306,34 +290,4 @@ describe("getControllerAPIEndpointErrors", () => {
"controllerAPIEndpoint (example.com:80/api) must be an absolute path or begin with ws:// or wss://.",
);
});

it("should show console error when dispatching connectAndStartPolling", async () => {
vi.spyOn(appThunks, "connectAndStartPolling").mockImplementation(
vi.fn().mockReturnValue({ type: "connectAndStartPolling" }),
);
vi.spyOn(storeModule.default, "dispatch").mockImplementation(
(action) =>
(action instanceof Object &&
"type" in action &&
action.type === "connectAndStartPolling"
? Promise.reject(
new Error("Error while dispatching connectAndStartPolling!"),
)
: null) as unknown as UnknownAction,
);
const config = configFactory.build({
baseControllerURL: null,
identityProviderURL: "/candid",
isJuju: true,
});
window.jujuDashboardConfig = config;
renderApp();
expect(appThunks.connectAndStartPolling).toHaveBeenCalledTimes(1);
await waitFor(() =>
expect(log.error).toHaveBeenCalledWith(
Label.POLLING_ERROR,
new Error("Error while dispatching connectAndStartPolling!"),
),
);
});
});
Loading

0 comments on commit 46b2aca

Please sign in to comment.