π OpenHands: AI-Driven Development
test(frontend): add unit tests (#1076)
sp.wack5881857d5c49
diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsxdeleted file mode 100644index d76787ed69..0000000000--- a/frontend/src/App.test.tsx+++ /dev/null@@ -1,9 +0,0 @@-import React from "react";-import { render, screen } from "@testing-library/react";-import App from "./App";--test("renders learn react link", () => {- render(<App />);- const linkElement = screen.getByText(/learn react/i);- expect(linkElement).toBeInTheDocument();-});diff --git a/frontend/src/hooks/useInputComposition.test.ts b/frontend/src/hooks/useInputComposition.test.tsnew file mode 100644index 0000000000..c1669666cf--- /dev/null+++ b/frontend/src/hooks/useInputComposition.test.ts@@ -0,0 +1,35 @@+import { act, renderHook } from "@testing-library/react";+import useInputComposition from "./useInputComposition";++describe("useInputComposition", () => {+ it("should return isComposing as false by default", () => {+ const { result } = renderHook(() => useInputComposition());+ expect(result.current.isComposing).toBe(false);+ });++ it("should set isComposing to true when onCompositionStart is called", () => {+ const { result } = renderHook(() => useInputComposition());++ act(() => {+ result.current.onCompositionStart();+ });++ expect(result.current.isComposing).toBe(true);+ });++ it("should set isComposing to false when onCompositionEnd is called", () => {+ const { result } = renderHook(() => useInputComposition());++ act(() => {+ result.current.onCompositionStart();+ });++ expect(result.current.isComposing).toBe(true);++ act(() => {+ result.current.onCompositionEnd();+ });++ expect(result.current.isComposing).toBe(false);+ });+});diff --git a/frontend/src/hooks/useTypingEffect.test.ts b/frontend/src/hooks/useTypingEffect.test.tsnew file mode 100644index 0000000000..b9cd31c3a8--- /dev/null+++ b/frontend/src/hooks/useTypingEffect.test.ts@@ -0,0 +1,150 @@+import { renderHook, act } from "@testing-library/react";+import { useTypingEffect } from "./useTypingEffect";++jest.useFakeTimers();++describe("useTypingEffect", () => {+ // This test fails because the hook improperly handles this case.+ it.skip("should handle empty strings array", () => {+ const { result } = renderHook(() => useTypingEffect([]));++ // Immediately check the result since there's nothing to type+ expect(result.current).toBe("\u00A0"); // Non-breaking space+ });++ it("should type out a string correctly", () => {+ const message = "Hello, world! This is a test message.";++ const { result } = renderHook(() => useTypingEffect([message]));++ // msg.length - 2 because the first two characters are typed immediately+ // 100ms per character, 0.1 playbackRate+ const msToRun = (message.length - 2) * 100 * 0.1;++ // Fast-forward time by to simulate typing message+ act(() => {+ jest.advanceTimersByTime(msToRun - 1); // exclude the last character for testing+ });++ expect(result.current).toBe(message.slice(0, -1));++ act(() => {+ jest.advanceTimersByTime(1); // include the last character+ });++ expect(result.current).toBe(message);+ });++ it("should type of a string correctly with a different playback rate", () => {+ const message = "Hello, world! This is a test message.";+ const playbackRate = 0.5;++ const { result } = renderHook(() =>+ useTypingEffect([message], { playbackRate }),+ );++ const msToRun = (message.length - 2) * 100 * playbackRate;++ act(() => {+ jest.advanceTimersByTime(msToRun - 1); // exclude the last character for testing+ });++ expect(result.current).toBe(message.slice(0, -1));++ act(() => {+ jest.advanceTimersByTime(1); // include the last character+ });++ expect(result.current).toBe(message);+ });++ it("should loop through strings when multiple are provided", () => {+ const messages = ["Hello", "World"];++ const { result } = renderHook(() => useTypingEffect(messages));++ const msToRunFirstString = messages[0].length * 100 * 0.1;++ // Fast-forward to end of first string+ act(() => {+ jest.advanceTimersByTime(msToRunFirstString);+ });++ expect(result.current).toBe(messages[0]); // Hello++ // Fast-forward through the delay and through the second string+ act(() => {+ // TODO: Improve to clarify the expected timing+ jest.runAllTimers();+ });++ expect(result.current).toBe(messages[1]); // World+ });++ it("should call setTypingActive with false when typing completes without loop", () => {+ const setTypingActiveMock = jest.fn();++ renderHook(() =>+ useTypingEffect(["Hello, world!", "This is a test message."], {+ loop: false,+ setTypingActive: setTypingActiveMock,+ }),+ );++ expect(setTypingActiveMock).not.toHaveBeenCalled();++ act(() => {+ jest.runAllTimers();+ });++ expect(setTypingActiveMock).toHaveBeenCalledWith(false);+ expect(setTypingActiveMock).toHaveBeenCalledTimes(1);+ });++ it("should call addAssistantMessageToChat with the typeThis argument when typing completes without loop", () => {+ const addAssistantMessageToChatMock = jest.fn();++ renderHook(() =>+ useTypingEffect(["Hello, world!", "This is a test message."], {+ loop: false,+ // Note that only "Hello, world!" is typed out (the first string in the array)+ typeThis: { content: "Hello, world!", sender: "assistant" },+ addAssistantMessageToChat: addAssistantMessageToChatMock,+ }),+ );++ expect(addAssistantMessageToChatMock).not.toHaveBeenCalled();++ act(() => {+ jest.runAllTimers();+ });++ expect(addAssistantMessageToChatMock).toHaveBeenCalledTimes(1);+ expect(addAssistantMessageToChatMock).toHaveBeenCalledWith({+ content: "Hello, world!",+ sender: "assistant",+ });+ });++ it("should call takeOneAndType when typing completes without loop", () => {+ const takeOneAndTypeMock = jest.fn();++ renderHook(() =>+ useTypingEffect(["Hello, world!", "This is a test message."], {+ loop: false,+ takeOneAndType: takeOneAndTypeMock,+ }),+ );++ expect(takeOneAndTypeMock).not.toHaveBeenCalled();++ act(() => {+ jest.runAllTimers();+ });++ expect(takeOneAndTypeMock).toHaveBeenCalledTimes(1);+ });++ // Implementation is not clear on how to handle this case+ it.todo("should handle typing with loop");+});diff --git a/frontend/src/services/auth.test.ts b/frontend/src/services/auth.test.tsnew file mode 100644index 0000000000..8021b5efa8--- /dev/null+++ b/frontend/src/services/auth.test.ts@@ -0,0 +1,85 @@+import * as jose from "jose";+import { fetchToken, validateToken, getToken } from "./auth";++jest.mock("jose", () => ({+ decodeJwt: jest.fn(),+}));++// SUGGESTION: Prefer using msw for mocking requests (see https://mswjs.io/)+global.fetch = jest.fn(() =>+ Promise.resolve({+ status: 200,+ json: () => Promise.resolve({ token: "newToken" }),+ }),+) as jest.Mock;++describe("Auth Service", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ Storage.prototype.getItem = jest.fn();+ Storage.prototype.setItem = jest.fn();+ });++ describe("fetchToken", () => {+ it("should fetch and return a token", async () => {+ const data = await fetchToken();++ expect(localStorage.getItem).toHaveBeenCalledWith("token"); // Used to set Authorization header+ expect(data).toEqual({ token: "newToken" });+ expect(fetch).toHaveBeenCalledWith(`/api/auth`, {+ headers: expect.any(Headers),+ });+ });++ it("throws an error if response status is not 200", async () => {+ (fetch as jest.Mock).mockImplementationOnce(() =>+ Promise.resolve({ status: 401 }),+ );+ await expect(fetchToken()).rejects.toThrow("Get token failed.");+ });+ });++ describe("validateToken", () => {+ it("returns true for a valid token", () => {+ (jose.decodeJwt as jest.Mock).mockReturnValue({ sid: "123" });+ expect(validateToken("validToken")).toBe(true);+ });++ it("returns false for an invalid token", () => {+ (jose.decodeJwt as jest.Mock).mockReturnValue({});+ expect(validateToken("invalidToken")).toBe(false);+ });++ it("returns false when decodeJwt throws", () => {+ (jose.decodeJwt as jest.Mock).mockImplementation(() => {+ throw new Error("Invalid token");+ });+ expect(validateToken("badToken")).toBe(false);+ });+ });++ describe("getToken", () => {+ it("returns existing valid token from localStorage", async () => {+ (jose.decodeJwt as jest.Mock).mockReturnValue({ sid: "123" });+ (Storage.prototype.getItem as jest.Mock).mockReturnValue("existingToken");++ const token = await getToken();+ expect(token).toBe("existingToken");+ });++ it("fetches, validates, and stores a new token when existing token is invalid", async () => {+ (jose.decodeJwt as jest.Mock)+ .mockReturnValueOnce({})+ .mockReturnValueOnce({ sid: "123" });++ const token = await getToken();+ expect(token).toBe("newToken");+ expect(localStorage.setItem).toHaveBeenCalledWith("token", "newToken");+ });++ it("throws an error when fetched token is invalid", async () => {+ (jose.decodeJwt as jest.Mock).mockReturnValue({});+ await expect(getToken()).rejects.toThrow("Token validation failed.");+ });+ });+});diff --git a/frontend/src/services/auth.ts b/frontend/src/services/auth.tsindex 71bfe2d3ad..4f9ba870a1 100644--- a/frontend/src/services/auth.ts+++ b/frontend/src/services/auth.ts@@ -14,7 +14,7 @@ const fetchToken = async (): Promise<ResFetchToken> => {return data;};-const validateToken = (token: string): boolean => {+export const validateToken = (token: string): boolean => {try {const claims = jose.decodeJwt(token);return !(claims.sid === undefined || claims.sid === "");diff --git a/frontend/src/services/session.test.ts b/frontend/src/services/session.test.tsnew file mode 100644index 0000000000..aa75e21f96--- /dev/null+++ b/frontend/src/services/session.test.ts@@ -0,0 +1,126 @@+import {+ ResDelMsg,+ ResFetchMsg,+ ResFetchMsgTotal,+ ResFetchMsgs,+} from "../types/ResponseType";+import { clearMsgs, fetchMsgTotal, fetchMsgs } from "./session";++// SUGGESTION: Prefer using msw for mocking requests (see https://mswjs.io/)+global.fetch = jest.fn();+Storage.prototype.getItem = jest.fn();++describe("Session Service", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ afterEach(() => {+ // Used to set Authorization header+ expect(localStorage.getItem).toHaveBeenCalledWith("token");+ });++ describe("fetchMsgTotal", () => {+ it("should fetch and return message total", async () => {+ const expectedResult: ResFetchMsgTotal = {+ msg_total: 10,+ };++ (fetch as jest.Mock).mockImplementationOnce(() =>+ Promise.resolve({+ status: 200,+ json: () => Promise.resolve(expectedResult),+ }),+ );++ const data = await fetchMsgTotal();++ expect(fetch).toHaveBeenCalledWith(`/api/messages/total`, {+ headers: expect.any(Headers),+ });++ expect(data).toEqual(expectedResult);+ });++ it("throws an error if response status is not 200", async () => {+ // NOTE: The current implementation ONLY handles 200 status;+ // this means throwing even with a status of 201, 204, etc.+ (fetch as jest.Mock).mockImplementationOnce(() =>+ Promise.resolve({ status: 401 }),+ );++ await expect(fetchMsgTotal()).rejects.toThrow(+ "Get message total failed.",+ );+ });+ });++ describe("fetchMsgs", () => {+ it("should fetch and return messages", async () => {+ const expectedResult: ResFetchMsgs = {+ messages: [+ {+ id: "1",+ role: "admin",+ payload: {} as ResFetchMsg["payload"],+ },+ ],+ };++ (fetch as jest.Mock).mockImplementationOnce(() =>+ Promise.resolve({+ status: 200,+ json: () => Promise.resolve(expectedResult),+ }),+ );++ const data = await fetchMsgs();++ expect(fetch).toHaveBeenCalledWith(`/api/messages`, {+ headers: expect.any(Headers),+ });++ expect(data).toEqual(expectedResult);+ });++ it("throws an error if response status is not 200", async () => {+ (fetch as jest.Mock).mockImplementationOnce(() =>+ Promise.resolve({ status: 401 }),+ );++ await expect(fetchMsgs()).rejects.toThrow("Get messages failed.");+ });+ });++ describe("clearMsgs", () => {+ it("should clear messages", async () => {+ const expectedResult: ResDelMsg = {+ ok: "true",+ };++ (fetch as jest.Mock).mockImplementationOnce(() =>+ Promise.resolve({+ status: 200,+ json: () => Promise.resolve(expectedResult),+ }),+ );++ const data = await clearMsgs();++ expect(fetch).toHaveBeenCalledWith(`/api/messages`, {+ method: "DELETE",+ headers: expect.any(Headers),+ });++ expect(data).toEqual(expectedResult);+ });++ it("throws an error if response status is not 200", async () => {+ (fetch as jest.Mock).mockImplementationOnce(() =>+ Promise.resolve({ status: 401 }),+ );++ await expect(clearMsgs()).rejects.toThrow("Delete messages failed.");+ });+ });+});diff --git a/frontend/src/services/settingsService.test.ts b/frontend/src/services/settingsService.test.tsnew file mode 100644index 0000000000..f0dcc77a00--- /dev/null+++ b/frontend/src/services/settingsService.test.ts@@ -0,0 +1,109 @@+import { mergeAndUpdateSettings } from "./settingsService";+import { ArgConfigType } from "../types/ConfigType";++// We need to mock this to avoid `SyntaxError` from using `Socket` in `settingsService` during testing+jest.mock("./socket", () => ({+ send: jest.fn(),+}));++describe("mergeAndUpdateSettings", () => {+ it("should return initial settings if newSettings is empty", () => {+ const oldSettings = { key1: "value1" };+ const isInit = false;++ const result = mergeAndUpdateSettings({}, oldSettings, isInit);++ expect(result.mergedSettings).toEqual(oldSettings);+ expect(result.updatedSettings).toEqual({});+ });++ it("should add new keys to mergedSettings and updatedSettings", () => {+ const oldSettings = { key1: "value1" };+ const newSettings = { key2: "value2" };+ const isInit = false;++ const result = mergeAndUpdateSettings(newSettings, oldSettings, isInit);++ expect(result.mergedSettings).toEqual({+ key1: "value1",+ key2: "value2",+ });+ expect(result.updatedSettings).toEqual({+ key2: "value2", // New key+ });+ });++ it("should overwrite non-DISPLAY_MAP keys in mergedSettings", () => {+ const oldSettings = { key1: "value1" };+ const newSettings = { key1: "newvalue1" };+ const isInit = false;++ const result = mergeAndUpdateSettings(newSettings, oldSettings, isInit);++ expect(result.mergedSettings).toEqual({ key1: "newvalue1" });+ expect(result.updatedSettings).toEqual({});+ });++ it("should keep old values in mergedSettings if they are equal", () => {+ const oldSettings = {+ [ArgConfigType.LLM_MODEL]: "gpt-4-0125-preview",+ [ArgConfigType.AGENT]: "MonologueAgent",+ };+ const newSettings = {+ [ArgConfigType.AGENT]: "MonologueAgent",+ };+ const isInit = false;++ const result = mergeAndUpdateSettings(newSettings, oldSettings, isInit);++ expect(result.mergedSettings).toEqual(oldSettings);+ expect(result.updatedSettings).toEqual({});+ });++ it("should keep old values in mergedSettings if isInit is true and old value is not empty", () => {+ const oldSettings = {+ [ArgConfigType.LLM_MODEL]: "gpt-4-0125-preview",+ [ArgConfigType.AGENT]: "MonologueAgent",+ };+ const newSettings = {+ [ArgConfigType.AGENT]: "MonologueAgent",+ };+ const isInit = true;++ const result = mergeAndUpdateSettings(newSettings, oldSettings, isInit);++ expect(result.mergedSettings).toEqual(oldSettings);+ expect(result.updatedSettings).toEqual({});+ });++ it("should update mergedSettings, updatedSettings and set needToSend to true for relevant changes", () => {+ const oldSettings = {+ [ArgConfigType.LLM_MODEL]: "gpt-4-0125-preview",+ [ArgConfigType.AGENT]: "MonologueAgent",+ key1: "value1",+ };+ const newSettings = {+ [ArgConfigType.AGENT]: "CodeActAgent",+ [ArgConfigType.LANGUAGE]: "es",+ key1: "newvalue1",+ key2: "value2",+ };+ const isInit = false;++ const result = mergeAndUpdateSettings(newSettings, oldSettings, isInit);++ expect(result.mergedSettings).toEqual({+ [ArgConfigType.LLM_MODEL]: "gpt-4-0125-preview",+ [ArgConfigType.AGENT]: "CodeActAgent", // Updated value+ [ArgConfigType.LANGUAGE]: "es", // New key added+ key1: "newvalue1", // Updated value+ key2: "value2", // New key added+ });+ expect(result.updatedSettings).toEqual({+ [ArgConfigType.AGENT]: "CodeActAgent",+ [ArgConfigType.LANGUAGE]: "es",+ key2: "value2",+ });+ expect(result.needToSend).toBe(true);+ });+});diff --git a/frontend/src/services/settingsService.ts b/frontend/src/services/settingsService.tsindex 6d80b32102..6bad460787 100644--- a/frontend/src/services/settingsService.ts+++ b/frontend/src/services/settingsService.ts@@ -52,15 +52,19 @@ const DISPLAY_MAP = new Map<string, string>([[ArgConfigType.LANGUAGE, "language"],]);-// Send settings to the server-export function saveSettings(- newSettings: { [key: string]: string },- oldSettings: { [key: string]: string },- isInit: boolean = false,-): void {- const { mergedSettings, updatedSettings, needToSend } = Object.keys(- newSettings,- ).reduce(+type SettingsUpdateInfo = {+ mergedSettings: Record<string, string>;+ updatedSettings: Record<string, string>;+ needToSend: boolean;+};++// Function to merge and update settings+export const mergeAndUpdateSettings = (+ newSettings: Record<string, string>,+ oldSettings: Record<string, string>,+ isInit: boolean,+) =>+ Object.keys(newSettings).reduce((acc, key) => {const newValue = String(newSettings[key]);const oldValue = oldSettings[key];@@ -71,6 +75,7 @@ export function saveSettings(acc.updatedSettings[key] = newValue;return acc;}+if (!DISPLAY_MAP.has(key)) {acc.mergedSettings[key] = newValue;return acc;@@ -91,13 +96,10 @@ export function saveSettings(mergedSettings: { ...oldSettings },updatedSettings: {},needToSend: false,- } as {- mergedSettings: { [key: string]: string };- updatedSettings: { [key: string]: string };- needToSend: boolean;- },+ } as SettingsUpdateInfo,);+const dispatchSettings = (updatedSettings: Record<string, string>) => {let i = 0;for (const [key, value] of Object.entries(updatedSettings)) {if (DISPLAY_MAP.has(key)) {@@ -108,16 +110,38 @@ export function saveSettings(i += 1;}}+};- if (isInit) {- store.dispatch(setAllSettings(JSON.stringify(newSettings)));- }+const sendSettings = (+ mergedSettings: Record<string, string>,+ needToSend: boolean,+ isInit: boolean,+) => {+ const settingsCopy = { ...mergedSettings };+ delete settingsCopy.ALL_SETTINGS;- delete mergedSettings.ALL_SETTINGS;if (needToSend || isInit) {- const event = { action: ActionType.INIT, args: mergedSettings };+ const event = { action: ActionType.INIT, args: settingsCopy };const eventString = JSON.stringify(event);store.dispatch(setInitialized(false));Socket.send(eventString);}+};++// Save and send settings to the server+export function saveSettings(+ newSettings: { [key: string]: string },+ oldSettings: { [key: string]: string },+ isInit: boolean = false,+): void {+ const { mergedSettings, updatedSettings, needToSend } =+ mergeAndUpdateSettings(newSettings, oldSettings, isInit);++ dispatchSettings(updatedSettings);++ if (isInit) {+ store.dispatch(setAllSettings(JSON.stringify(newSettings)));+ }++ sendSettings(mergedSettings, needToSend, isInit);}diff --git a/frontend/src/utils/storage.test.ts b/frontend/src/utils/storage.test.tsnew file mode 100644index 0000000000..264cbdfd9f--- /dev/null+++ b/frontend/src/utils/storage.test.ts@@ -0,0 +1,27 @@+import { getCachedConfig } from "./storage";++describe("getCachedConfig", () => {+ beforeEach(() => {+ // Clear all instances and calls to constructor and all methods+ Storage.prototype.getItem = jest.fn();+ });++ it("should return an empty object when local storage is null or undefined", () => {+ (Storage.prototype.getItem as jest.Mock).mockReturnValue(null);+ expect(getCachedConfig()).toEqual({});++ (Storage.prototype.getItem as jest.Mock).mockReturnValue(undefined);+ expect(getCachedConfig()).toEqual({});+ });++ it("should return an empty object when local storage has invalid JSON", () => {+ (Storage.prototype.getItem as jest.Mock).mockReturnValue("invalid JSON");+ expect(getCachedConfig()).toEqual({});+ });++ it("should return parsed object when local storage has valid JSON", () => {+ const validJSON = '{"key":"value"}';+ (Storage.prototype.getItem as jest.Mock).mockReturnValue(validJSON);+ expect(getCachedConfig()).toEqual({ key: "value" });+ });+});