Repository navigation
[Customer Portal][FE][Web] Implement get chat history API with test cases for both mock and real environments #100
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Rashmika998
merged 7 commits into
wso2-open-operations:customer-portal-milestone-1
from
dileepapeiris:feat/add-support-outstanding-cases-chat-history
Feb 9, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a581cf2
Add tests for useGetChatHistory hook
dileepapeiris 7f6c964
Add useGetChatHistory React Query hook
dileepapeiris 7139b25
Add CHAT_HISTORY to ApiQueryKeys
dileepapeiris 9378301
Add mock chat history generator
dileepapeiris 78612dd
Add chat history response models
dileepapeiris fe75bde
Extract mock chat history into mockData
dileepapeiris ad7117d
Merge branch 'customer-portal-milestone-1' into feat/add-support-outs…
Rashmika998 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
211 changes: 211 additions & 0 deletions
211
apps/customer-portal/webapp/src/api/__tests__/useGetChatHistory.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,211 @@ | ||
| // Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). | ||
| // | ||
| // WSO2 LLC. licenses this file to you under the Apache License, | ||
| // Version 2.0 (the "License"); you may not use this file except | ||
| // in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| import { renderHook, waitFor } from "@testing-library/react"; | ||
| import { beforeEach, describe, expect, it, vi } from "vitest"; | ||
| import { useGetChatHistory } from "@api/useGetChatHistory"; | ||
| import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; | ||
| import type { ReactNode } from "react"; | ||
|
|
||
| const mockLogger = { | ||
| debug: vi.fn(), | ||
| error: vi.fn(), | ||
| }; | ||
| vi.mock("@/hooks/useLogger", () => ({ | ||
| useLogger: () => mockLogger, | ||
| })); | ||
|
|
||
| vi.mock("@/constants/apiConstants", async (importOriginal) => { | ||
| const actual = (await importOriginal()) as Record<string, unknown>; | ||
| return { | ||
| ...actual, | ||
| API_MOCK_DELAY: 0, | ||
| }; | ||
| }); | ||
|
|
||
| const mockGetIdToken = vi.fn().mockResolvedValue("mock-token"); | ||
| vi.mock("@asgardeo/react", () => ({ | ||
| useAsgardeo: () => ({ | ||
| getIdToken: mockGetIdToken, | ||
| isSignedIn: true, | ||
| isLoading: false, | ||
| }), | ||
| })); | ||
|
|
||
| let mockIsMockEnabled = true; | ||
| vi.mock("@/providers/MockConfigProvider", () => ({ | ||
| useMockConfig: () => ({ | ||
| isMockEnabled: mockIsMockEnabled, | ||
| }), | ||
| })); | ||
|
|
||
| describe("useGetChatHistory", () => { | ||
| let queryClient: QueryClient; | ||
|
|
||
| beforeEach(() => { | ||
| queryClient = new QueryClient({ | ||
| defaultOptions: { | ||
| queries: { | ||
| retry: false, | ||
| }, | ||
| }, | ||
| }); | ||
| mockLogger.debug.mockClear(); | ||
| mockLogger.error.mockClear(); | ||
| mockIsMockEnabled = true; | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| const wrapper = ({ children }: { children: ReactNode }) => ( | ||
| <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> | ||
| ); | ||
|
|
||
| it("should return loading state initially", async () => { | ||
| const { result } = renderHook( | ||
| () => useGetChatHistory("project-1"), | ||
| { wrapper }, | ||
| ); | ||
|
|
||
| expect(result.current.isLoading).toBe(true); | ||
| }); | ||
|
|
||
| it("should return mock data when mock is enabled", async () => { | ||
| mockIsMockEnabled = true; | ||
| const { result } = renderHook( | ||
| () => useGetChatHistory("project-1"), | ||
| { wrapper }, | ||
| ); | ||
|
|
||
| await waitFor(() => expect(result.current.isSuccess).toBe(true)); | ||
|
|
||
| expect(result.current.data).toBeDefined(); | ||
| expect(result.current.data?.chatHistory).toBeDefined(); | ||
| expect(Array.isArray(result.current.data?.chatHistory)).toBe(true); | ||
| expect(result.current.data?.chatHistory.length).toBeGreaterThan(0); | ||
| expect(result.current.data?.chatHistory[0]).toMatchObject({ | ||
| chatId: expect.any(String), | ||
| title: expect.any(String), | ||
| startedTime: expect.any(String), | ||
| messages: expect.any(Number), | ||
| kbArticles: expect.any(Number), | ||
| status: expect.any(String), | ||
| }); | ||
| expect(mockLogger.debug).toHaveBeenCalledWith( | ||
| expect.stringContaining( | ||
| "Fetching chat history for project ID: project-1, mock: true", | ||
| ), | ||
| ); | ||
| }); | ||
|
|
||
| it("should have correct query options", () => { | ||
| renderHook(() => useGetChatHistory("project-1"), { wrapper }); | ||
|
|
||
| const query = queryClient.getQueryCache().findAll({ | ||
| queryKey: ["chat-history", "project-1", true], | ||
| })[0]; | ||
|
|
||
| expect((query?.options as { staleTime?: number }).staleTime).toBe( | ||
| 5 * 60 * 1000, | ||
| ); | ||
| }); | ||
|
|
||
| it("should fetch real data when mock is disabled", async () => { | ||
| mockIsMockEnabled = false; | ||
| const mockResponse = { | ||
| chatHistory: [ | ||
| { | ||
| chatId: "1", | ||
| title: "Test chat", | ||
| startedTime: "1 hour ago", | ||
| messages: 3, | ||
| kbArticles: 1, | ||
| status: "Resolved", | ||
| }, | ||
| ], | ||
| }; | ||
|
|
||
| const originalConfig = window.config; | ||
| window.config = { | ||
| CUSTOMER_PORTAL_BACKEND_BASE_URL: "https://api.test", | ||
| } as typeof window.config; | ||
|
|
||
| vi.stubGlobal( | ||
| "fetch", | ||
| vi.fn().mockResolvedValue({ | ||
| ok: true, | ||
| json: () => Promise.resolve(mockResponse), | ||
| status: 200, | ||
| } as Response), | ||
| ); | ||
|
|
||
| const { result } = renderHook( | ||
| () => useGetChatHistory("project-1"), | ||
| { wrapper }, | ||
| ); | ||
|
|
||
| await waitFor(() => expect(result.current.isSuccess).toBe(true)); | ||
|
|
||
| expect(result.current.data).toEqual(mockResponse); | ||
| expect(mockGetIdToken).toHaveBeenCalled(); | ||
| expect(mockLogger.debug).toHaveBeenCalledWith( | ||
| expect.stringContaining( | ||
| "Fetching chat history for project ID: project-1, mock: false", | ||
| ), | ||
| ); | ||
|
|
||
| window.config = originalConfig; | ||
| }); | ||
|
|
||
| it("should handle API error when mock is disabled", async () => { | ||
| mockIsMockEnabled = false; | ||
|
|
||
| const originalConfig = window.config; | ||
| window.config = { | ||
| CUSTOMER_PORTAL_BACKEND_BASE_URL: "https://api.test", | ||
| } as typeof window.config; | ||
|
|
||
| vi.stubGlobal( | ||
| "fetch", | ||
| vi.fn().mockResolvedValue({ | ||
| ok: false, | ||
| statusText: "Internal Server Error", | ||
| status: 500, | ||
| } as Response), | ||
| ); | ||
|
|
||
| const { result } = renderHook( | ||
| () => useGetChatHistory("project-1"), | ||
| { wrapper }, | ||
| ); | ||
|
|
||
| await waitFor(() => expect(result.current.isError).toBe(true)); | ||
| expect(result.current.error?.message).toContain( | ||
| "Error fetching chat history: Internal Server Error", | ||
| ); | ||
| expect(mockLogger.error).toHaveBeenCalled(); | ||
|
|
||
| window.config = originalConfig; | ||
| }); | ||
|
|
||
| it("should not fetch if projectId is missing", () => { | ||
| const { result } = renderHook(() => useGetChatHistory(""), { | ||
| wrapper, | ||
| }); | ||
|
|
||
| expect(result.current.isLoading).toBe(false); | ||
| expect(result.current.fetchStatus).toBe("idle"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| // Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). | ||
| // | ||
| // WSO2 LLC. licenses this file to you under the Apache License, | ||
| // Version 2.0 (the "License"); you may not use this file except | ||
| // in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| import { useQuery, type UseQueryResult } from "@tanstack/react-query"; | ||
| import { useAsgardeo } from "@asgardeo/react"; | ||
| import { getMockChatHistory } from "@models/mockFunctions"; | ||
| import { useMockConfig } from "@providers/MockConfigProvider"; | ||
| import { useLogger } from "@hooks/useLogger"; | ||
| import { ApiQueryKeys, API_MOCK_DELAY } from "@constants/apiConstants"; | ||
| import { addApiHeaders } from "@utils/apiUtils"; | ||
| import type { ChatHistoryResponse } from "@models/responses"; | ||
|
|
||
| /** | ||
| * Fetches chat history for a project. | ||
| * | ||
| * @param {string} projectId - The project ID. | ||
| * @returns {UseQueryResult<ChatHistoryResponse, Error>} The query result. | ||
| */ | ||
| export function useGetChatHistory( | ||
| projectId: string, | ||
| ): UseQueryResult<ChatHistoryResponse, Error> { | ||
| const logger = useLogger(); | ||
| const { getIdToken, isSignedIn, isLoading: isAuthLoading } = useAsgardeo(); | ||
| const { isMockEnabled } = useMockConfig(); | ||
|
|
||
| return useQuery<ChatHistoryResponse, Error>({ | ||
| queryKey: [ApiQueryKeys.CHAT_HISTORY, projectId, isMockEnabled], | ||
| queryFn: async (): Promise<ChatHistoryResponse> => { | ||
| logger.debug( | ||
| `Fetching chat history for project ID: ${projectId}, mock: ${isMockEnabled}`, | ||
| ); | ||
|
|
||
| if (isMockEnabled) { | ||
| await new Promise((resolve) => setTimeout(resolve, API_MOCK_DELAY)); | ||
| const data = getMockChatHistory(); | ||
| logger.debug( | ||
| `Chat history fetched successfully for project ID: ${projectId} (mock)`, | ||
| data, | ||
| ); | ||
| return data; | ||
| } | ||
|
|
||
| try { | ||
| const idToken = await getIdToken(); | ||
| const baseUrl = window.config?.CUSTOMER_PORTAL_BACKEND_BASE_URL; | ||
|
|
||
| if (!baseUrl) { | ||
| throw new Error("CUSTOMER_PORTAL_BACKEND_BASE_URL is not configured"); | ||
| } | ||
|
|
||
| const requestUrl = `${baseUrl}/projects/${projectId}/chat-history`; | ||
|
|
||
| const response = await fetch(requestUrl, { | ||
| method: "GET", | ||
| headers: addApiHeaders(idToken), | ||
| }); | ||
|
|
||
| logger.debug( | ||
| `[useGetChatHistory] Response status: ${response.status}`, | ||
| ); | ||
|
|
||
| if (!response.ok) { | ||
| throw new Error( | ||
| `Error fetching chat history: ${response.statusText}`, | ||
| ); | ||
| } | ||
|
|
||
| const data: ChatHistoryResponse = await response.json(); | ||
| logger.debug("[useGetChatHistory] Data received:", data); | ||
| return data; | ||
| } catch (error) { | ||
| logger.error("[useGetChatHistory] Error:", error); | ||
| throw error; | ||
| } | ||
| }, | ||
| enabled: !!projectId && (isMockEnabled || (isSignedIn && !isAuthLoading)), | ||
| staleTime: 5 * 60 * 1000, | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.