Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Drop usage of cancelable and add unit tests (#65455)

Frasere02de4a3bb6f
diff --git a/frontend/src/metabase/common/components/ActionButton/ActionButton.tsx b/frontend/src/metabase/common/components/ActionButton/ActionButton.tsx
index 244229c26c4..661dc0c3cb6 100644
--- a/frontend/src/metabase/common/components/ActionButton/ActionButton.tsx
+++ b/frontend/src/metabase/common/components/ActionButton/ActionButton.tsx
@@ -12,8 +12,6 @@ import { t } from "ttag";
import Button, { type ButtonProps } from "metabase/common/components/Button";
import ButtonsS from "metabase/css/components/buttons.module.css";
import CS from "metabase/css/core/index.css";
-import type { CancellablePromise } from "metabase/lib/promise";
-import { cancelable } from "metabase/lib/promise";
import { Center, Group, Icon, Loader } from "metabase/ui";
export interface ActionButtonProps extends Omit<ButtonProps, "onClick"> {
@@ -56,21 +54,19 @@ const ActionButton = forwardRef<ActionButtonHandle, ActionButtonProps>(
const [active, setActive] = useState(false);
const [result, setResult] = useState<null | "failed" | "success">(null);
const timeout = useRef<null | ReturnType<typeof setTimeout>>(null);
- const actionPromise = useRef<CancellablePromise<unknown> | null>(null);
+ const isMountedRef = useRef(true);
const resetTimeout = () => {
timeout.current && clearTimeout(timeout.current);
};
useEffect(() => {
- const promise = actionPromise.current;
+ isMountedRef.current = true;
return () => {
+ isMountedRef.current = false;
resetTimeout();
- if (promise) {
- promise?.cancel?.();
- }
};
- }, [actionPromise]);
+ }, []);
const resetState = useCallback(() => {
resetTimeout();
@@ -95,15 +91,16 @@ const ActionButton = forwardRef<ActionButtonHandle, ActionButtonProps>(
setResult(null);
// run the function we want bound to this button
- actionPromise.current = cancelable(actionFn());
- actionPromise.current.then(
+ actionFn().then(
() => {
- setActive(false);
- setResult("success");
- resetStateOnTimeout();
+ if (isMountedRef.current) {
+ setActive(false);
+ setResult("success");
+ resetStateOnTimeout();
+ }
},
- (error: Error & { isCanceled?: boolean }) => {
- if (!error.isCanceled) {
+ (error: Error) => {
+ if (isMountedRef.current) {
console.error(error);
setActive(false);
setResult("failed");
diff --git a/frontend/src/metabase/common/components/ActionButton/ActionButton.unit.spec.tsx b/frontend/src/metabase/common/components/ActionButton/ActionButton.unit.spec.tsx
new file mode 100644
index 00000000000..47727103fd8
--- /dev/null
+++ b/frontend/src/metabase/common/components/ActionButton/ActionButton.unit.spec.tsx
@@ -0,0 +1,196 @@
+import { act } from "@testing-library/react";
+import { useRef } from "react";
+
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+
+import ActionButton, {
+ type ActionButtonHandle,
+ type ActionButtonProps,
+} from "./ActionButton";
+
+const setup = async (props: Partial<ActionButtonProps> = {}) => {
+ const actionFn = jest.fn().mockResolvedValue(undefined);
+
+ const defaultProps: ActionButtonProps = {
+ actionFn,
+ ...props,
+ };
+
+ renderWithProviders(<ActionButton {...defaultProps} />);
+
+ return { actionFn };
+};
+
+const setupWithRef = async (props: Partial<ActionButtonProps> = {}) => {
+ const actionFn = jest.fn().mockResolvedValue(undefined);
+ let resetStateFn: (() => void) | null = null;
+
+ const TestComponent = () => {
+ const ref = useRef<ActionButtonHandle>(null);
+
+ resetStateFn = () => ref.current?.resetState();
+
+ return <ActionButton ref={ref} actionFn={actionFn} {...props} />;
+ };
+
+ renderWithProviders(<TestComponent />);
+
+ return {
+ actionFn,
+ resetState: () => resetStateFn?.(),
+ };
+};
+
+describe("ActionButton", () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it("should render with default normalText", async () => {
+ await setup({});
+
+ expect(screen.getByRole("button", { name: "Save" })).toBeInTheDocument();
+ });
+
+ it("should render with custom normalText", async () => {
+ await setup({ normalText: "Submit" });
+
+ expect(screen.getByRole("button", { name: "Submit" })).toBeInTheDocument();
+ });
+
+ it("should render children instead of normalText when provided", async () => {
+ await setup({ children: <span>Custom Button</span> });
+
+ expect(screen.getByText("Custom Button")).toBeInTheDocument();
+ });
+
+ it("should handle successful action flow", async () => {
+ const { actionFn } = await setup({
+ normalText: "Save",
+ activeText: "Saving...",
+ successText: "Saved!",
+ });
+
+ const button = screen.getByRole("button");
+ expect(screen.getByText("Save")).toBeInTheDocument();
+ expect(button).toHaveAttribute("data-action-status", "idle");
+
+ act(() => {
+ button.click();
+ });
+
+ expect(await screen.findByText("Saving...")).toBeInTheDocument();
+ expect(button).toHaveAttribute("data-action-status", "pending");
+ expect(actionFn).toHaveBeenCalledTimes(1);
+ expect(await screen.findByText("Saved!")).toBeInTheDocument();
+ expect(screen.getByLabelText("check icon")).toBeInTheDocument();
+ expect(button).toHaveAttribute("data-action-status", "success");
+
+ act(() => {
+ jest.advanceTimersByTime(5000);
+ });
+
+ expect(await screen.findByText("Save")).toBeInTheDocument();
+ expect(button).toHaveAttribute("data-action-status", "idle");
+ });
+
+ it("should handle successful action flow with loading spinner", async () => {
+ const { actionFn } = await setup({
+ useLoadingSpinner: true,
+ });
+
+ const button = screen.getByRole("button");
+
+ act(() => {
+ button.click();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();
+ });
+ expect(actionFn).toHaveBeenCalledTimes(1);
+ expect(await screen.findByText("Saved")).toBeInTheDocument();
+ });
+
+ it("should handle failed action flow", async () => {
+ const actionFn = jest.fn().mockRejectedValue(new Error("Test error"));
+ const consoleErrorSpy = jest
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ await setup({
+ actionFn,
+ normalText: "Save",
+ activeText: "Saving...",
+ failedText: "Failed!",
+ });
+
+ const button = screen.getByRole("button");
+
+ expect(screen.getByText("Save")).toBeInTheDocument();
+ expect(button).toHaveAttribute("data-action-status", "idle");
+
+ act(() => {
+ button.click();
+ });
+
+ expect(await screen.findByText("Saving...")).toBeInTheDocument();
+ expect(button).toHaveAttribute("data-action-status", "pending");
+ expect(actionFn).toHaveBeenCalledTimes(1);
+
+ expect(await screen.findByText("Failed!")).toBeInTheDocument();
+ expect(button).toHaveAttribute("data-action-status", "failed");
+ expect(consoleErrorSpy).toHaveBeenCalled();
+
+ act(() => {
+ jest.advanceTimersByTime(5000);
+ });
+
+ expect(await screen.findByText("Save")).toBeInTheDocument();
+ expect(button).toHaveAttribute("data-action-status", "idle");
+
+ consoleErrorSpy.mockRestore();
+ });
+
+ it("should reset state when resetState is called via ref and clear timeout", async () => {
+ const { resetState } = await setupWithRef({});
+
+ const button = screen.getByRole("button");
+ act(() => {
+ button.click();
+ });
+
+ expect(await screen.findByText("Saved")).toBeInTheDocument();
+
+ act(() => {
+ resetState();
+ jest.advanceTimersByTime(5000);
+ });
+
+ // Should be back to normal state immediately, and stay there even after timer would have fired
+ expect(screen.getByText("Save")).toBeInTheDocument();
+ });
+
+ it("should cancel promise on unmount", async () => {
+ const actionFn = jest.fn().mockReturnValue(
+ new Promise((resolve) => {
+ setTimeout(resolve, 10000);
+ }),
+ );
+
+ const { unmount } = renderWithProviders(
+ <ActionButton actionFn={actionFn} />,
+ );
+
+ const button = screen.getByRole("button");
+ button.click();
+
+ unmount();
+
+ expect(actionFn).toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/metabase/lib/promise.ts b/frontend/src/metabase/lib/promise.ts
index 0943890413e..d4ab152e081 100644
--- a/frontend/src/metabase/lib/promise.ts
+++ b/frontend/src/metabase/lib/promise.ts
@@ -1,41 +1,5 @@
import { noop } from "underscore";
-export type CancellablePromise<T> = Promise<T> & {
- cancel: () => void;
-};
-
-/**
- * @deprecated - this is stupid don't use it
- * returns a promise wrapping the provided one but with a "cancel" method
- */
-export function cancelable<T>(promise: Promise<T>): CancellablePromise<T> {
- let canceled = false;
-
- const wrappedPromise = new Promise<T>((resolve, reject) => {
- promise.then(
- (value) => (canceled ? reject({ isCanceled: true }) : resolve(value)),
- (error) => (canceled ? reject({ isCanceled: true }) : reject(error)),
- );
- });
-
- return Object.assign(wrappedPromise, { cancel: () => (canceled = true) });
-}
-
-// if a promise doesn't resolve/reject within a given duration it will reject
-export function timeout(
- promise: Promise<unknown>,
- duration: number,
- error: unknown,
-) {
- return new Promise((resolve, reject) => {
- promise.then(resolve, reject);
- setTimeout(
- () => reject(error || new Error("Operation timed out")),
- duration,
- );
- });
-}
-
// returns a promise that resolves after a given duration
export function delay(duration: number) {
return new Promise((resolve) => setTimeout(resolve, duration));