Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

chore: test coverage in frontend/utils (#3826)

Myles Scolnickdf1585c23e67
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 93a45cd2ac..06c5711f41 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -17,7 +17,7 @@ import {
useEventListener,
} from "@/hooks/useEventListener";
import { MarimoIncomingMessageEvent } from "@/core/dom/events";
-import { updateBufferPaths } from "@/utils/date-views";
+import { updateBufferPaths } from "@/utils/data-views";
interface Data {
jsUrl: string;
diff --git a/frontend/src/utils/__tests__/Deferred.test.ts b/frontend/src/utils/__tests__/Deferred.test.ts
new file mode 100644
index 0000000000..c889d1810d
--- /dev/null
+++ b/frontend/src/utils/__tests__/Deferred.test.ts
@@ -0,0 +1,38 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { Deferred } from "../Deferred";
+
+describe("Deferred", () => {
+ it("should resolve correctly", async () => {
+ const deferred = new Deferred<number>();
+ expect(deferred.status).toBe("pending");
+
+ const value = 42;
+ deferred.resolve(value);
+ expect(deferred.status).toBe("resolved");
+
+ const result = await deferred.promise;
+ expect(result).toBe(value);
+ });
+
+ it("should reject correctly", async () => {
+ const deferred = new Deferred<number>();
+ expect(deferred.status).toBe("pending");
+
+ const error = new Error("test error");
+ deferred.reject(error);
+ expect(deferred.status).toBe("rejected");
+
+ await expect(deferred.promise).rejects.toThrow(error);
+ });
+
+ it("should handle promise-like values in resolve", async () => {
+ const deferred = new Deferred<string>();
+ const promiseValue = Promise.resolve("test");
+ deferred.resolve(promiseValue);
+ expect(deferred.status).toBe("resolved");
+
+ const result = await deferred.promise;
+ expect(result).toBe("test");
+ });
+});
diff --git a/frontend/src/utils/__tests__/arrays.test.ts b/frontend/src/utils/__tests__/arrays.test.ts
new file mode 100644
index 0000000000..605ab4bf1c
--- /dev/null
+++ b/frontend/src/utils/__tests__/arrays.test.ts
@@ -0,0 +1,130 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import {
+ arrayDelete,
+ arrayInsert,
+ arrayMove,
+ arrayInsertMany,
+ arrayShallowEquals,
+ Arrays,
+ arrayToggle,
+} from "../arrays";
+
+describe("arrays", () => {
+ describe("arrayDelete", () => {
+ it("should delete an element at the specified index", () => {
+ expect(arrayDelete([1, 2, 3], 1)).toEqual([1, 3]);
+ });
+
+ it("should handle first and last elements", () => {
+ expect(arrayDelete([1, 2, 3], 0)).toEqual([2, 3]);
+ expect(arrayDelete([1, 2, 3], 2)).toEqual([1, 2]);
+ });
+ });
+
+ describe("arrayInsert", () => {
+ it("should insert an element at the specified index", () => {
+ expect(arrayInsert([1, 2, 3], 1, 4)).toEqual([1, 4, 2, 3]);
+ });
+
+ it("should clamp index to array bounds", () => {
+ expect(arrayInsert([1, 2, 3], -1, 4)).toEqual([4, 1, 2, 3]);
+ expect(arrayInsert([1, 2, 3], 5, 4)).toEqual([1, 2, 3, 4]);
+ });
+
+ it("should handle empty arrays", () => {
+ expect(arrayInsert([], 0, 1)).toEqual([1]);
+ });
+ });
+
+ describe("arrayMove", () => {
+ it("should move an element from one index to another", () => {
+ expect(arrayMove([1, 2, 3], 0, 2)).toEqual([2, 3, 1]);
+ expect(arrayMove([1, 2, 3], 2, 0)).toEqual([3, 1, 2]);
+ });
+
+ it("should handle adjacent moves", () => {
+ expect(arrayMove([1, 2, 3], 0, 1)).toEqual([2, 1, 3]);
+ expect(arrayMove([1, 2, 3], 1, 0)).toEqual([2, 1, 3]);
+ });
+ });
+
+ describe("arrayInsertMany", () => {
+ it("should insert multiple elements at the specified index", () => {
+ expect(arrayInsertMany([1, 2, 3], 1, [4, 5])).toEqual([1, 4, 5, 2, 3]);
+ });
+
+ it("should handle empty target array", () => {
+ expect(arrayInsertMany([], 0, [1, 2])).toEqual([1, 2]);
+ });
+
+ it("should handle empty insert array", () => {
+ expect(arrayInsertMany([1, 2, 3], 1, [])).toEqual([1, 2, 3]);
+ });
+
+ it("should clamp index to array bounds", () => {
+ expect(arrayInsertMany([1, 2, 3], -1, [4, 5])).toEqual([4, 5, 1, 2, 3]);
+ expect(arrayInsertMany([1, 2, 3], 5, [4, 5])).toEqual([1, 2, 3, 4, 5]);
+ });
+ });
+
+ describe("arrayShallowEquals", () => {
+ it("should return true for identical arrays", () => {
+ expect(arrayShallowEquals([1, 2, 3], [1, 2, 3])).toBe(true);
+ });
+
+ it("should return false for arrays with different lengths", () => {
+ expect(arrayShallowEquals([1, 2], [1, 2, 3])).toBe(false);
+ });
+
+ it("should return false for arrays with same length but different elements", () => {
+ expect(arrayShallowEquals([1, 2, 3], [1, 2, 4])).toBe(false);
+ });
+
+ it("should handle empty arrays", () => {
+ expect(arrayShallowEquals([], [])).toBe(true);
+ });
+
+ it("should use strict equality for objects", () => {
+ const obj = { a: 1 };
+ expect(arrayShallowEquals([obj], [obj])).toBe(true);
+ expect(arrayShallowEquals([obj], [{ a: 1 }])).toBe(false);
+ });
+ });
+
+ describe("Arrays.zip", () => {
+ it("should zip two arrays of equal length", () => {
+ expect(Arrays.zip([1, 2], ["a", "b"])).toEqual([
+ [1, "a"],
+ [2, "b"],
+ ]);
+ });
+
+ it("should throw for arrays of different lengths", () => {
+ expect(() => Arrays.zip([1, 2], ["a"])).toThrow();
+ });
+
+ it("should handle empty arrays", () => {
+ expect(Arrays.zip([], [])).toEqual([]);
+ });
+ });
+
+ describe("arrayToggle", () => {
+ it("should add item if not present", () => {
+ expect(arrayToggle([1, 2], 3)).toEqual([1, 2, 3]);
+ });
+
+ it("should remove item if present", () => {
+ expect(arrayToggle([1, 2, 3], 2)).toEqual([1, 3]);
+ });
+
+ it("should handle undefined/null array", () => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ expect(arrayToggle(undefined as any, 1)).toEqual([1]);
+ });
+
+ it("should handle empty array", () => {
+ expect(arrayToggle([], 1)).toEqual([1]);
+ });
+ });
+});
diff --git a/frontend/src/utils/__tests__/date-views.test.ts b/frontend/src/utils/__tests__/data-views.test.ts
similarity index 96%
rename from frontend/src/utils/__tests__/date-views.test.ts
rename to frontend/src/utils/__tests__/data-views.test.ts
index dba1186f00..27c0efda06 100644
--- a/frontend/src/utils/__tests__/date-views.test.ts
+++ b/frontend/src/utils/__tests__/data-views.test.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, it, expect } from "vitest";
-import { updateBufferPaths, base64ToDataView } from "../date-views";
+import { updateBufferPaths, base64ToDataView } from "../data-views";
describe("updateBufferPaths", () => {
it("should return the original object if bufferPaths is null", () => {
diff --git a/frontend/src/utils/__tests__/errors.test.ts b/frontend/src/utils/__tests__/errors.test.ts
new file mode 100644
index 0000000000..f86bbb4cb4
--- /dev/null
+++ b/frontend/src/utils/__tests__/errors.test.ts
@@ -0,0 +1,49 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { prettyError } from "../errors";
+
+describe("prettyError", () => {
+ it("handles null/undefined errors", () => {
+ expect(prettyError(null)).toBe("Unknown error");
+ expect(prettyError(undefined)).toBe("Unknown error");
+ });
+
+ it("extracts details from Error objects with cause", () => {
+ const error = new Error("Original message");
+ error.cause = { detail: "Detailed error message" };
+ expect(prettyError(error)).toBe("Detailed error message");
+ });
+
+ it("extracts details from Error message if JSON", () => {
+ const error = new Error('{"detail": "JSON error message"}');
+ expect(prettyError(error)).toBe("JSON error message");
+ });
+
+ it("returns original message if not JSON", () => {
+ const error = new Error("Plain error message");
+ expect(prettyError(error)).toBe("Plain error message");
+ });
+
+ it("handles objects with detail property", () => {
+ const error = { detail: "Object error message" };
+ expect(prettyError(error)).toBe("Object error message");
+ });
+
+ it("stringifies plain objects", () => {
+ const error = { foo: "bar" };
+ expect(prettyError(error)).toBe('{"foo":"bar"}');
+ });
+
+ it("handles primitive values", () => {
+ expect(prettyError(123)).toBe("123");
+ expect(prettyError("string error")).toBe('"string error"');
+ expect(prettyError(true)).toBe("true");
+ });
+
+ it("handles circular references", () => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const circular: any = { foo: "bar" };
+ circular.self = circular;
+ expect(prettyError(circular)).toBe("[object Object]");
+ });
+});
diff --git a/frontend/src/utils/__tests__/maps.test.ts b/frontend/src/utils/__tests__/maps.test.ts
new file mode 100644
index 0000000000..274affd3a8
--- /dev/null
+++ b/frontend/src/utils/__tests__/maps.test.ts
@@ -0,0 +1,91 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { Maps } from "../maps";
+
+describe("Maps", () => {
+ describe("keyBy", () => {
+ it("should create a map from an array using a key function", () => {
+ const items = [
+ { id: "1", value: "a" },
+ { id: "2", value: "b" },
+ ];
+ const result = Maps.keyBy(items, (item) => item.id);
+ expect(result.get("1")).toEqual({ id: "1", value: "a" });
+ expect(result.get("2")).toEqual({ id: "2", value: "b" });
+ });
+
+ it("should handle duplicate keys by keeping the last value", () => {
+ const items = [
+ { id: "1", value: "a" },
+ { id: "1", value: "b" },
+ ];
+ const result = Maps.keyBy(items, (item) => item.id);
+ expect(result.size).toBe(1);
+ expect(result.get("1")).toEqual({ id: "1", value: "b" });
+ });
+ });
+
+ describe("collect", () => {
+ it("should create a map with transformed values", () => {
+ const items = [
+ { id: "1", value: "a" },
+ { id: "2", value: "b" },
+ ];
+ const result = Maps.collect(
+ items,
+ (item) => item.id,
+ (item) => item.value.toUpperCase(),
+ );
+ expect(result.get("1")).toBe("A");
+ expect(result.get("2")).toBe("B");
+ });
+ });
+
+ describe("filterMap", () => {
+ it("should filter map entries based on predicate", () => {
+ const map = new Map([
+ ["1", "a"],
+ ["2", "b"],
+ ["3", "c"],
+ ]);
+ const result = Maps.filterMap(map, (value) => value !== "b");
+ expect(result.size).toBe(2);
+ expect(result.get("1")).toBe("a");
+ expect(result.get("2")).toBeUndefined();
+ expect(result.get("3")).toBe("c");
+ });
+
+ it("should handle predicate with key", () => {
+ const map = new Map([
+ ["1", "a"],
+ ["2", "b"],
+ ["3", "c"],
+ ]);
+ const result = Maps.filterMap(map, (_, key) => key !== "2");
+ expect(result.size).toBe(2);
+ expect([...result.keys()]).toEqual(["1", "3"]);
+ });
+ });
+
+ describe("mapValues", () => {
+ it("should transform map values using mapper function", () => {
+ const map = new Map([
+ ["1", "a"],
+ ["2", "b"],
+ ]);
+ const result = Maps.mapValues(map, (value) => value.toUpperCase());
+ expect(result.get("1")).toBe("A");
+ expect(result.get("2")).toBe("B");
+ });
+
+ it("should handle mapper with key", () => {
+ const map = new Map([
+ ["1", "a"],
+ ["2", "b"],
+ ]);
+ const result = Maps.mapValues(map, (value, key) => `${key}:${value}`);
+ expect(result.get("1")).toBe("1:a");
+ expect(result.get("2")).toBe("2:b");
+ });
+ });
+});
diff --git a/frontend/src/utils/__tests__/math.test.ts b/frontend/src/utils/__tests__/math.test.ts
new file mode 100644
index 0000000000..7850d0403f
--- /dev/null
+++ b/frontend/src/utils/__tests__/math.test.ts
@@ -0,0 +1,29 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { clamp } from "../math";
+
+describe("math utils", () => {
+ describe("clamp", () => {
+ it("should return value when within bounds", () => {
+ expect(clamp(5, 0, 10)).toBe(5);
+ });
+
+ it("should return min when value is below", () => {
+ expect(clamp(-5, 0, 10)).toBe(0);
+ });
+
+ it("should return max when value is above", () => {
+ expect(clamp(15, 0, 10)).toBe(10);
+ });
+
+ it("should handle equal min/max bounds", () => {
+ expect(clamp(5, 10, 10)).toBe(10);
+ });
+
+ it("should handle decimal values", () => {
+ expect(clamp(1.5, 1, 2)).toBe(1.5);
+ expect(clamp(0.5, 1, 2)).toBe(1);
+ expect(clamp(2.5, 1, 2)).toBe(2);
+ });
+ });
+});
diff --git a/frontend/src/utils/__tests__/pluralize.test.ts b/frontend/src/utils/__tests__/pluralize.test.ts
new file mode 100644
index 0000000000..e49ef6ee85
--- /dev/null
+++ b/frontend/src/utils/__tests__/pluralize.test.ts
@@ -0,0 +1,47 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, test, expect } from "vitest";
+import { PluralWord, PluralWords } from "../pluralize";
+
+describe("PluralWord", () => {
+ test("should use default plural form (adding 's')", () => {
+ const word = new PluralWord("cat");
+ expect(word.plural).toBe("cats");
+ expect(word.pluralize(1)).toBe("cat");
+ expect(word.pluralize(2)).toBe("cats");
+ });
+
+ test("should use custom plural form", () => {
+ const word = new PluralWord("child", "children");
+ expect(word.plural).toBe("children");
+ expect(word.pluralize(1)).toBe("child");
+ expect(word.pluralize(2)).toBe("children");
+ });
+
+ test("should handle zero as plural", () => {
+ const word = new PluralWord("dog");
+ expect(word.pluralize(0)).toBe("dogs");
+ });
+});
+
+describe("PluralWords", () => {
+ test("should create from strings", () => {
+ const words = PluralWords.of("cat", "dog");
+ expect(words.join(" and ", 1)).toBe("cat and dog");
+ expect(words.join(" and ", 2)).toBe("cats and dogs");
+ });
+
+ test("should create from PluralWord instances", () => {
+ const words = PluralWords.of(
+ new PluralWord("child", "children"),
+ new PluralWord("mouse", "mice"),
+ );
+ expect(words.join(", ", 1)).toBe("child, mouse");
+ expect(words.join(", ", 2)).toBe("children, mice");
+ });
+
+ test("should mix strings and PluralWord instances", () => {
+ const words = PluralWords.of("cat", new PluralWord("person", "people"));
+ expect(words.join(" and ", 1)).toBe("cat and person");
+ expect(words.join(" and ", 2)).toBe("cats and people");
+ });
+});
diff --git a/frontend/src/utils/__tests__/sets.test.ts b/frontend/src/utils/__tests__/sets.test.ts
new file mode 100644
index 0000000000..2752104423
--- /dev/null
+++ b/frontend/src/utils/__tests__/sets.test.ts
@@ -0,0 +1,41 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { Sets } from "../sets";
+
+describe("Sets", () => {
+ describe("merge", () => {
+ it("should merge empty sets", () => {
+ const result = Sets.merge(new Set(), new Set());
+ expect(result.size).toBe(0);
+ });
+
+ it("should merge sets with unique values", () => {
+ const set1 = new Set([1, 2]);
+ const set2 = new Set([3, 4]);
+ const result = Sets.merge(set1, set2);
+ expect([...result]).toEqual([1, 2, 3, 4]);
+ });
+
+ it("should handle overlapping values", () => {
+ const set1 = new Set([1, 2, 3]);
+ const set2 = new Set([2, 3, 4]);
+ const result = Sets.merge(set1, set2);
+ expect([...result]).toEqual([1, 2, 3, 4]);
+ });
+
+ it("should merge multiple sets", () => {
+ const set1 = new Set([1]);
+ const set2 = new Set([2]);
+ const set3 = new Set([3]);
+ const result = Sets.merge(set1, set2, set3);
+ expect([...result]).toEqual([1, 2, 3]);
+ });
+
+ it("should handle sets with different types", () => {
+ const set1 = new Set(["a", "b"]);
+ const set2 = new Set(["b", "c"]);
+ const result = Sets.merge(set1, set2);
+ expect([...result]).toEqual(["a", "b", "c"]);
+ });
+ });
+});
diff --git a/frontend/src/utils/__tests__/strings.test.ts b/frontend/src/utils/__tests__/strings.test.ts
new file mode 100644
index 0000000000..81441d7675
--- /dev/null
+++ b/frontend/src/utils/__tests__/strings.test.ts
@@ -0,0 +1,68 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { Strings, decodeUtf8 } from "../strings";
+
+describe("Strings", () => {
+ describe("startCase", () => {
+ it("handles empty string", () => {
+ expect(Strings.startCase("")).toBe("");
+ });
+
+ it("handles non-letter strings", () => {
+ expect(Strings.startCase("123")).toBe("123");
+ expect(Strings.startCase("!@#")).toBe("!@#");
+ });
+
+ it("converts strings to start case", () => {
+ expect(Strings.startCase("hello world")).toBe("Hello World");
+ expect(Strings.startCase("camelCase")).toBe("Camel Case");
+ expect(Strings.startCase("snake_case")).toBe("Snake Case");
+ });
+
+ it("throws for non-string input", () => {
+ expect(() => Strings.startCase(123 as unknown as string)).toThrow();
+ });
+ });
+
+ describe("htmlEscape", () => {
+ it("handles undefined", () => {
+ expect(Strings.htmlEscape(undefined)).toBeUndefined();
+ });
+
+ it("handles empty string", () => {
+ expect(Strings.htmlEscape("")).toBe("");
+ });
+
+ it("escapes HTML special characters", () => {
+ expect(Strings.htmlEscape("< > & \" ' \n")).toBe(
+ "&lt; &gt; &amp; &quot; &#039; ",
+ );
+ expect(Strings.htmlEscape("<script>alert('xss')</script>")).toBe(
+ "&lt;script&gt;alert(&#039;xss&#039;)&lt;/script&gt;",
+ );
+ });
+ });
+
+ describe("withoutTrailingSlash", () => {
+ it("removes trailing slash", () => {
+ expect(Strings.withoutTrailingSlash("/path/")).toBe("/path");
+ expect(Strings.withoutTrailingSlash("/path")).toBe("/path");
+ });
+ });
+
+ describe("withoutLeadingSlash", () => {
+ it("removes leading slash", () => {
+ expect(Strings.withoutLeadingSlash("/path")).toBe("path");
+ expect(Strings.withoutLeadingSlash("path")).toBe("path");
+ });
+ });
+});
+
+describe("decodeUtf8", () => {
+ it("decodes UTF-8 array to string", () => {
+ const encoder = new TextEncoder();
+ const text = "Hello 世界";
+ const encoded = encoder.encode(text);
+ expect(decodeUtf8(encoded)).toBe(text);
+ });
+});
diff --git a/frontend/src/utils/__tests__/versions.test.ts b/frontend/src/utils/__tests__/versions.test.ts
index a18988f75c..03ee7b45f4 100644
--- a/frontend/src/utils/__tests__/versions.test.ts
+++ b/frontend/src/utils/__tests__/versions.test.ts
@@ -1,6 +1,10 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, it, expect } from "vitest";
-import { semverSort } from "../versions";
+import {
+ cleanPythonModuleName,
+ reverseSemverSort,
+ semverSort,
+} from "../versions";
describe("semverSort", () => {
it("should sort versions correctly", () => {
@@ -39,4 +43,21 @@ describe("semverSort", () => {
"1.0.0+exp.sha.5114f85",
]);
});
+
+ it("reverseSemverSort", () => {
+ const versions = ["1.0.0", "1.0.1", "1.0.10", "1.0.2"];
+ const sortedVersions = versions.sort(reverseSemverSort);
+ expect(sortedVersions).toEqual(["1.0.10", "1.0.2", "1.0.1", "1.0.0"]);
+ });
+});
+
+it("cleanPythonModuleName", () => {
+ expect(cleanPythonModuleName("pandas[excel]")).toBe("pandas");
+ expect(cleanPythonModuleName("ibis-framework[duckdb]")).toBe(
+ "ibis-framework",
+ );
+ expect(cleanPythonModuleName("package[opt1,opt2]")).toBe("package");
+
+ expect(cleanPythonModuleName(" pandas[excel] ")).toBe("pandas");
+ expect(cleanPythonModuleName("\tpkg[opt]\n")).toBe("pkg");
});
diff --git a/frontend/src/utils/__tests__/waitForWs.test.ts b/frontend/src/utils/__tests__/waitForWs.test.ts
new file mode 100644
index 0000000000..c13cd9bf1a
--- /dev/null
+++ b/frontend/src/utils/__tests__/waitForWs.test.ts
@@ -0,0 +1,76 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { beforeEach, afterEach, expect, describe, it, vi } from "vitest";
+import { waitForWs } from "../waitForWs";
+
+describe("waitForWs", () => {
+ let originalWebSocket: typeof WebSocket;
+ let mockWs: any;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ originalWebSocket = global.WebSocket;
+ mockWs = {
+ close: vi.fn(),
+ onopen: null,
+ onerror: null,
+ };
+ global.WebSocket = vi.fn(() => mockWs) as any;
+ });
+
+ afterEach(() => {
+ global.WebSocket = originalWebSocket;
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ it("resolves immediately on successful connection", async () => {
+ const url = "ws://test.com";
+ const promise = waitForWs(url);
+
+ // Simulate successful connection
+ mockWs.onopen();
+
+ await expect(promise).resolves.toBe(url);
+ expect(mockWs.close).toHaveBeenCalled();
+ expect(global.WebSocket).toHaveBeenCalledTimes(1);
+ expect(global.WebSocket).toHaveBeenCalledWith(url);
+ });
+
+ it("retries on failure with linear backoff", async () => {
+ const url = "ws://test.com";
+ const promise = waitForWs(url, 3);
+
+ // First attempt fails
+ mockWs.onerror(new Event("error"));
+ await vi.advanceTimersByTimeAsync(1000);
+
+ // Second attempt fails
+ mockWs.onerror(new Event("error"));
+ await vi.advanceTimersByTimeAsync(2000);
+
+ // Third attempt succeeds
+ mockWs.onopen();
+
+ await expect(promise).resolves.toBe(url);
+ expect(global.WebSocket).toHaveBeenCalledTimes(3);
+ expect(mockWs.close).toHaveBeenCalledTimes(3);
+ });
+
+ it("throws after max retries", async () => {
+ const url = "ws://test.com";
+ const promise = waitForWs(url, 2).catch((error) => error);
+
+ // First attempt fails
+ mockWs.onerror(new Event("error"));
+ await vi.advanceTimersByTimeAsync(1000);
+
+ // Second attempt fails
+ mockWs.onerror(new Event("error"));
+ await vi.advanceTimersByTimeAsync(2000);
+
+ expect((await promise).message).toBe(`Failed to connect to ${url}`);
+ expect(global.WebSocket).toHaveBeenCalledTimes(2);
+ expect(mockWs.close).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/frontend/src/utils/__tests__/waitForWs.ts b/frontend/src/utils/__tests__/waitForWs.ts
deleted file mode 100644
index 6a81eb68a3..0000000000
--- a/frontend/src/utils/__tests__/waitForWs.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-/* eslint-disable @typescript-eslint/no-explicit-any */
-import { beforeAll, afterAll, expect, describe, it, vi } from "vitest";
-import { waitForWs } from "../waitForWs";
-
-describe("waitForWs", () => {
- let originalWebSocket: any;
-
- beforeAll(() => {
- // Save the original WebSocket object
- originalWebSocket = global.WebSocket;
- });
-
- afterAll(() => {
- // Restore the original WebSocket object after tests
- global.WebSocket = originalWebSocket;
- });
-
- it("should resolve when the WebSocket connection is successful", async () => {
- // Mock the WebSocket object
- global.WebSocket = vi.fn().mockImplementation((url) => ({
- onopen: null,
- onerror: null,
- close: vi.fn(),
- })) as any;
-
- const url = "ws://localhost:3000";
- await expect(waitForWs(url)).resolves.toBe(url);
-
- // Verify that WebSocket was called with the correct URL
- expect(global.WebSocket).toHaveBeenCalledWith(url);
- });
-
- it("should reject when the WebSocket connection fails", async () => {
- // Mock the WebSocket object
- global.WebSocket = vi.fn().mockImplementation((url) => ({
- onopen: null,
- onerror: null,
- close: vi.fn(),
- // Simulate a connection error
- simulateError: function () {
- if (this.onerror) {
- this.onerror(new Error("Connection error"));
- }
- },
- })) as any;
-
- const url = "ws://localhost:3000";
- const ws = new global.WebSocket(url);
- (ws as any).simulateError();
-
- await expect(waitForWs(url)).rejects.toThrow(`Failed to connect to ${url}`);
-
- // Verify that WebSocket was called with the correct URL
- expect(global.WebSocket).toHaveBeenCalledWith(url);
- });
-});
diff --git a/frontend/src/utils/date-views.ts b/frontend/src/utils/data-views.ts
similarity index 100%
rename from frontend/src/utils/date-views.ts
rename to frontend/src/utils/data-views.ts
diff --git a/frontend/src/utils/errors.ts b/frontend/src/utils/errors.ts
index 49963b764d..2ff2931726 100644
--- a/frontend/src/utils/errors.ts
+++ b/frontend/src/utils/errors.ts
@@ -22,7 +22,6 @@ export function prettyError(error: unknown): string {
if (details.success) {
return details.data.detail;
}
- return JSON.stringify(error);
}
try {
return JSON.stringify(error);