Frontend/test/chat 1 (#508)

* feat: add providers mocks

* test(<ChatPage/>: add render test using providers
This commit is contained in:
Mamadou DICKO 2023-07-05 09:30:22 +02:00 committed by GitHub
parent f4ba4d9d18
commit 9bb7ccf651
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 272 additions and 74 deletions

View File

@ -0,0 +1,61 @@
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import {
BrainConfigContextMock,
BrainConfigProviderMock,
} from "@/lib/context/BrainConfigProvider/mocks/BrainConfigProviderMock";
import {
BrainContextMock,
BrainProviderMock,
} from "@/lib/context/BrainProvider/mocks/BrainProviderMock";
import {
ChatContextMock,
ChatProviderMock,
} from "@/lib/context/ChatProvider/mocks/ChatProviderMock";
import {
SupabaseContextMock,
SupabaseProviderMock,
} from "@/lib/context/SupabaseProvider/mocks/SupabaseProviderMock";
import ChatPage from "../page";
vi.mock("@/lib/context/ChatProvider/ChatProvider", () => ({
ChatContext: ChatContextMock,
ChatProvider: ChatProviderMock,
}));
vi.mock("@/lib/context/SupabaseProvider/supabase-provider", () => ({
SupabaseContext: SupabaseContextMock,
}));
vi.mock("@/lib/context/BrainProvider/brain-provider", () => ({
BrainContext: BrainContextMock,
}));
vi.mock("@/lib/context/BrainConfigProvider/brain-config-provider", () => ({
BrainConfigContext: BrainConfigContextMock,
}));
describe("Chat page", () => {
it("should render chat page correctly", () => {
const { getByTestId, getByText } = render(
<SupabaseProviderMock>
<BrainConfigProviderMock>
<BrainProviderMock>
<ChatPage />,
</BrainProviderMock>
</BrainConfigProviderMock>
</SupabaseProviderMock>
);
expect(getByTestId("chat-page")).toBeDefined();
expect(getByTestId("chat-messages")).toBeDefined();
expect(getByTestId("chat-input")).toBeDefined();
expect(getByText("Chat with your brain")).toBeDefined();
expect(
getByText("Talk to a language model about your uploaded data")
).toBeDefined();
});
});

View File

@ -12,7 +12,8 @@ export const useChatMessages = () => {
const scrollToBottom = useCallback(() => { const scrollToBottom = useCallback(() => {
if (chatListRef.current) { if (chatListRef.current) {
chatListRef.current.scrollTo({ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
chatListRef.current.scrollTo?.({
top: chatListRef.current.scrollHeight, top: chatListRef.current.scrollHeight,
behavior: "smooth", behavior: "smooth",
}); });

View File

@ -14,6 +14,7 @@ export const ChatMessages = (): JSX.Element => {
<Card <Card
className="p-5 max-w-3xl w-full flex flex-col mb-8 overflow-y-auto scrollbar" className="p-5 max-w-3xl w-full flex flex-col mb-8 overflow-y-auto scrollbar"
ref={chatListRef} ref={chatListRef}
data-testid="chat-messages"
> >
<div className="flex-1"> <div className="flex-1">
{history.length === 0 ? ( {history.length === 0 ? (

View File

@ -1,3 +1,2 @@
export * from "./ChatInput"; export * from "./ChatInput";
export * from "./ChatMessages"; export * from "./ChatMessages";
export * from "./ChatMessages/components/ChatMessage/components/ChatMessage";

View File

@ -4,11 +4,11 @@ import { useParams } from "next/navigation";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useBrainConfig } from "@/lib/context/BrainConfigProvider/hooks/useBrainConfig"; import { useBrainConfig } from "@/lib/context/BrainConfigProvider/hooks/useBrainConfig";
import { useChatContext } from "@/lib/context/ChatProvider/hooks/useChatContext";
import { useToast } from "@/lib/hooks"; import { useToast } from "@/lib/hooks";
import { useEventTracking } from "@/services/analytics/useEventTracking"; import { useEventTracking } from "@/services/analytics/useEventTracking";
import { useChatService } from "./useChatService"; import { useChatService } from "./useChatService";
import { useChatContext } from "../../../../lib/context/ChatProvider";
import { ChatQuestion } from "../types"; import { ChatQuestion } from "../types";
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types

View File

@ -3,9 +3,9 @@
import { useCallback } from "react"; import { useCallback } from "react";
import { useBrainContext } from "@/lib/context/BrainProvider/hooks/useBrainContext"; import { useBrainContext } from "@/lib/context/BrainProvider/hooks/useBrainContext";
import { useChatContext } from "@/lib/context/ChatProvider/hooks/useChatContext";
import { useAxios, useFetch } from "@/lib/hooks"; import { useAxios, useFetch } from "@/lib/hooks";
import { useChatContext } from "../../../../lib/context/ChatProvider";
import { ChatEntity, ChatHistory, ChatQuestion } from "../types"; import { ChatEntity, ChatHistory, ChatQuestion } from "../types";
interface UseChatService { interface UseChatService {

View File

@ -1,14 +1,13 @@
/* eslint-disable */
"use client"; "use client";
import PageHeading from "@/lib/components/ui/PageHeading"; import PageHeading from "@/lib/components/ui/PageHeading";
import { ChatProvider } from "@/lib/context/ChatProvider";
import { ChatProvider } from "../../../lib/context/ChatProvider";
import { ChatInput, ChatMessages } from "./components"; import { ChatInput, ChatMessages } from "./components";
export default function ChatPage() { const ChatPage = (): JSX.Element => {
return ( return (
<main className="flex flex-col w-full pt-10"> <main className="flex flex-col w-full pt-10" data-testid="chat-page">
<section className="flex flex-col flex-1 items-center w-full h-full min-h-[70vh]"> <section className="flex flex-col flex-1 items-center w-full h-full min-h-[70vh]">
<PageHeading <PageHeading
title="Chat with your brain" title="Chat with your brain"
@ -25,4 +24,6 @@ export default function ChatPage() {
</section> </section>
</main> </main>
); );
} };
export default ChatPage;

View File

@ -1,9 +1,9 @@
/* eslint-disable */
"use client"; "use client";
import { motion, MotionConfig } from "framer-motion";
import { MdChevronRight } from "react-icons/md";
import { useChatsContext } from "@/lib/context/ChatsProvider/hooks/useChatsContext"; import { useChatsContext } from "@/lib/context/ChatsProvider/hooks/useChatsContext";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { MotionConfig, motion } from "framer-motion";
import { MdChevronRight } from "react-icons/md";
import { ChatsListItem } from "./components/ChatsListItem"; import { ChatsListItem } from "./components/ChatsListItem";
import { MiniFooter } from "./components/ChatsListItem/components/MiniFooter"; import { MiniFooter } from "./components/ChatsListItem/components/MiniFooter";
@ -13,6 +13,7 @@ import { useChatsList } from "./hooks/useChatsList";
export const ChatsList = (): JSX.Element => { export const ChatsList = (): JSX.Element => {
const { allChats, deleteChat } = useChatsContext(); const { allChats, deleteChat } = useChatsContext();
const { open, setOpen } = useChatsList(); const { open, setOpen } = useChatsList();
return ( return (
<MotionConfig transition={{ mass: 1, damping: 10 }}> <MotionConfig transition={{ mass: 1, damping: 10 }}>
<motion.div <motion.div
@ -49,6 +50,7 @@ export const ChatsList = (): JSX.Element => {
<ChatsListItem <ChatsListItem
key={chat.chat_id} key={chat.chat_id}
chat={chat} chat={chat}
// eslint-disable-next-line @typescript-eslint/no-misused-promises
deleteChat={deleteChat} deleteChat={deleteChat}
/> />
))} ))}

View File

@ -7,8 +7,8 @@ import Footer from "@/lib/components/Footer";
import { NavBar } from "@/lib/components/NavBar"; import { NavBar } from "@/lib/components/NavBar";
import { TrackingWrapper } from "@/lib/components/TrackingWrapper"; import { TrackingWrapper } from "@/lib/components/TrackingWrapper";
import { ToastProvider } from "@/lib/components/ui/Toast"; import { ToastProvider } from "@/lib/components/ui/Toast";
import { BrainProvider } from "@/lib/context"; import { BrainConfigProvider } from "@/lib/context/BrainConfigProvider";
import { BrainConfigProvider } from "@/lib/context/BrainConfigProvider/brain-config-provider"; import { BrainProvider } from "@/lib/context/BrainProvider";
import { SupabaseProvider } from "@/lib/context/SupabaseProvider"; import { SupabaseProvider } from "@/lib/context/SupabaseProvider";
import "./globals.css"; import "./globals.css";

View File

@ -9,11 +9,11 @@ import {
getBrainConfigFromLocalStorage, getBrainConfigFromLocalStorage,
saveBrainConfigInLocalStorage, saveBrainConfigInLocalStorage,
} from "./helpers/brainConfigLocalStorage"; } from "./helpers/brainConfigLocalStorage";
import { BrainConfig, ConfigContext } from "./types"; import { BrainConfig, BrainConfigContextType } from "./types";
export const BrainConfigContext = createContext<ConfigContext | undefined>( export const BrainConfigContext = createContext<
undefined BrainConfigContextType | undefined
); >(undefined);
const defaultBrainConfig: BrainConfig = { const defaultBrainConfig: BrainConfig = {
model: "gpt-3.5-turbo-0613", model: "gpt-3.5-turbo-0613",

View File

@ -7,7 +7,7 @@ export const useBrainConfig = () => {
const context = useContext(BrainConfigContext); const context = useContext(BrainConfigContext);
if (context === undefined) { if (context === undefined) {
throw new Error("useConfig must be used inside SupabaseProvider"); throw new Error("useBrainConfig must be used inside BrainConfigProvider");
} }
return context; return context;

View File

@ -0,0 +1 @@
export * from "./brain-config-provider";

View File

@ -0,0 +1,28 @@
import { createContext, PropsWithChildren } from "react";
import { BrainConfigContextType } from "../types";
export const BrainConfigContextMock = createContext<
BrainConfigContextType | undefined
>(undefined);
export const BrainConfigProviderMock = ({
children,
}: PropsWithChildren): JSX.Element => {
return (
<BrainConfigContextMock.Provider
value={{
config: {
model: "gpt-3.5-turbo-0613",
temperature: 0,
maxTokens: 256,
keepLocal: true,
},
updateConfig: () => void 0,
resetConfig: () => void 0,
}}
>
{children}
</BrainConfigContextMock.Provider>
);
};

View File

@ -12,7 +12,7 @@ export type BrainConfig = {
type OptionalConfig = { [K in keyof BrainConfig]?: BrainConfig[K] | undefined }; type OptionalConfig = { [K in keyof BrainConfig]?: BrainConfig[K] | undefined };
export type ConfigContext = { export type BrainConfigContextType = {
config: BrainConfig; config: BrainConfig;
updateConfig: (config: OptionalConfig) => void; updateConfig: (config: OptionalConfig) => void;
resetConfig: () => void; resetConfig: () => void;

View File

@ -1,7 +1,13 @@
"use client"; "use client";
import { BrainContext } from "./hooks/useBrainContext"; import { createContext } from "react";
import { useBrainState } from "./hooks/useBrainState"; import { useBrainState } from "./hooks/useBrainState";
import { BrainContextType } from "./types";
export const BrainContext = createContext<BrainContextType | undefined>(
undefined
);
export const BrainProvider = ({ export const BrainProvider = ({
children, children,

View File

@ -1,9 +1,7 @@
import { createContext, useContext } from "react"; import { useContext } from "react";
import { BrainStateProps } from "./useBrainState"; import { BrainStateProps } from "./useBrainState";
import { ScopeContext } from "../types"; import { BrainContext } from "../brain-provider";
export const BrainContext = createContext<ScopeContext | undefined>(undefined);
export const useBrainContext = (): BrainStateProps => { export const useBrainContext = (): BrainStateProps => {
const context = useContext(BrainContext); const context = useContext(BrainContext);

View File

@ -0,0 +1,36 @@
import { createContext, PropsWithChildren } from "react";
import { BrainContextType } from "../types";
export const BrainContextMock = createContext<BrainContextType | undefined>(
undefined
);
export const BrainProviderMock = ({
children,
}: PropsWithChildren): JSX.Element => {
return (
<BrainContextMock.Provider
value={{
allBrains: [],
currentBrain: undefined,
//@ts-ignore we are not using the functions in tests
createBrain: () => void 0,
//@ts-ignore we are not using the functions in tests
deleteBrain: () => void 0,
//@ts-ignore we are not using the functions in tests
currentBrainId: undefined,
//@ts-ignore we are not using the functions in tests
fetchAllBrains: () => void 0,
//@ts-ignore we are not using the functions in tests
getBrainWithId: () => void 0,
//@ts-ignore we are not using the functions in tests
setActiveBrain: () => void 0,
//@ts-ignore we are not using the functions in tests
setDefaultBrain: () => void 0,
}}
>
{children}
</BrainContextMock.Provider>
);
};

View File

@ -14,4 +14,4 @@ export type Brain = {
temperature?: string; temperature?: string;
}; };
export type ScopeContext = ReturnType<typeof useBrainState>; export type BrainContextType = ReturnType<typeof useBrainState>;

View File

@ -1,16 +1,10 @@
"use client"; "use client";
import { createContext, useContext, useState } from "react"; import { createContext, useState } from "react";
import { ChatHistory } from "../../app/chat/[chatId]/types"; import { ChatHistory } from "@/app/chat/[chatId]/types";
type ChatContextProps = { import { ChatContextProps } from "./types";
history: ChatHistory[];
setHistory: (history: ChatHistory[]) => void;
addToHistory: (message: ChatHistory) => void;
updateHistory: (chat: ChatHistory) => void;
updateStreamingHistory: (streamedChat: ChatHistory) => void;
};
export const ChatContext = createContext<ChatContextProps | undefined>( export const ChatContext = createContext<ChatContextProps | undefined>(
undefined undefined
@ -29,7 +23,6 @@ export const ChatProvider = ({
const updateStreamingHistory = (streamedChat: ChatHistory): void => { const updateStreamingHistory = (streamedChat: ChatHistory): void => {
setHistory((prevHistory: ChatHistory[]) => { setHistory((prevHistory: ChatHistory[]) => {
console.log("new chat", streamedChat);
const updatedHistory = prevHistory.find( const updatedHistory = prevHistory.find(
(item) => item.message_id === streamedChat.message_id (item) => item.message_id === streamedChat.message_id
) )
@ -40,8 +33,6 @@ export const ChatProvider = ({
) )
: [...prevHistory, streamedChat]; : [...prevHistory, streamedChat];
console.log("updated history", updatedHistory);
return updatedHistory; return updatedHistory;
}); });
}; };
@ -76,13 +67,3 @@ export const ChatProvider = ({
</ChatContext.Provider> </ChatContext.Provider>
); );
}; };
export const useChatContext = (): ChatContextProps => {
const context = useContext(ChatContext);
if (context === undefined) {
throw new Error("useChatContext must be used inside ChatProvider");
}
return context;
};

View File

@ -0,0 +1,14 @@
import { useContext } from "react";
import { ChatContext } from "../ChatProvider";
import { ChatContextProps } from "../types";
export const useChatContext = (): ChatContextProps => {
const context = useContext(ChatContext);
if (context === undefined) {
throw new Error("useChatContext must be used inside ChatProvider");
}
return context;
};

View File

@ -0,0 +1,2 @@
export * from "./ChatProvider";
export * from "./hooks/useChatContext";

View File

@ -0,0 +1,25 @@
import { createContext, PropsWithChildren } from "react";
import { ChatContextProps } from "../types";
export const ChatContextMock = createContext<ChatContextProps | undefined>(
undefined
);
export const ChatProviderMock = ({
children,
}: PropsWithChildren): JSX.Element => {
return (
<ChatContextMock.Provider
value={{
history: [],
setHistory: () => void 0,
addToHistory: () => void 0,
updateHistory: () => void 0,
updateStreamingHistory: () => void 0,
}}
>
{children}
</ChatContextMock.Provider>
);
};

View File

@ -0,0 +1,9 @@
import { ChatHistory } from "@/app/chat/[chatId]/types";
export type ChatContextProps = {
history: ChatHistory[];
setHistory: (history: ChatHistory[]) => void;
addToHistory: (message: ChatHistory) => void;
updateHistory: (chat: ChatHistory) => void;
updateStreamingHistory: (streamedChat: ChatHistory) => void;
};

View File

@ -1,8 +1,8 @@
/* eslint-disable */
import { useContext } from "react"; import { useContext } from "react";
import { ChatsContext } from "../chats-provider"; import { ChatsContext } from "../chats-provider";
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const useChatsContext = () => { export const useChatsContext = () => {
const context = useContext(ChatsContext); const context = useContext(ChatsContext);

View File

@ -0,0 +1 @@
export * from "./chats-provider";

View File

@ -0,0 +1,14 @@
import { useContext } from "react";
import { SupabaseContext } from "../supabase-provider";
import { SupabaseContextType } from "../types";
export const useSupabase = (): SupabaseContextType => {
const context = useContext(SupabaseContext);
if (context === undefined) {
throw new Error("useSupabase must be used inside SupabaseProvider");
}
return context;
};

View File

@ -1 +1,2 @@
export * from "./hooks/useSupabase";
export * from "./supabase-provider"; export * from "./supabase-provider";

View File

@ -0,0 +1,24 @@
import { createContext, PropsWithChildren } from "react";
import { SupabaseContextType } from "../types";
export const SupabaseContextMock = createContext<
SupabaseContextType | undefined
>(undefined);
export const SupabaseProviderMock = ({
children,
}: PropsWithChildren): JSX.Element => {
return (
<SupabaseContextMock.Provider
value={{
// @ts-ignore - we are not actually using these values in the tests
supabase: {},
// @ts-ignore - we are not actually using these values in the tests
session: {},
}}
>
{children}
</SupabaseContextMock.Provider>
);
};

View File

@ -1,28 +1,24 @@
"use client"; "use client";
import type { SupabaseClient } from "@supabase/auth-helpers-nextjs";
import { import {
createBrowserSupabaseClient, createBrowserSupabaseClient,
Session, Session,
} from "@supabase/auth-helpers-nextjs"; } from "@supabase/auth-helpers-nextjs";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { createContext, useContext, useEffect, useState } from "react"; import { createContext, useEffect, useState } from "react";
type MaybeSession = Session | null; import { SupabaseContextType } from "./types";
export type SupabaseContext = { export const SupabaseContext = createContext<SupabaseContextType | undefined>(
supabase: SupabaseClient; undefined
session: MaybeSession; );
};
const Context = createContext<SupabaseContext | undefined>(undefined);
export const SupabaseProvider = ({ export const SupabaseProvider = ({
children, children,
session, session,
}: { }: {
children: React.ReactNode; children: React.ReactNode;
session: MaybeSession; session: Session | null;
}): JSX.Element => { }): JSX.Element => {
const [supabase] = useState(() => createBrowserSupabaseClient()); const [supabase] = useState(() => createBrowserSupabaseClient());
const router = useRouter(); const router = useRouter();
@ -40,18 +36,8 @@ export const SupabaseProvider = ({
}, [router, supabase]); }, [router, supabase]);
return ( return (
<Context.Provider value={{ supabase, session }}> <SupabaseContext.Provider value={{ supabase, session }}>
<>{children}</> <>{children}</>
</Context.Provider> </SupabaseContext.Provider>
); );
}; };
export const useSupabase = (): SupabaseContext => {
const context = useContext(Context);
if (context === undefined) {
throw new Error("useSupabase must be used inside SupabaseProvider");
}
return context;
};

View File

@ -0,0 +1,6 @@
import { Session, SupabaseClient } from "@supabase/auth-helpers-nextjs";
export type SupabaseContextType = {
supabase: SupabaseClient;
session: Session | null;
};

View File

@ -1,7 +1,7 @@
import axios, { AxiosError, AxiosInstance } from "axios"; import axios, { AxiosError, AxiosInstance } from "axios";
import { useBrainConfig } from "../context/BrainConfigProvider/hooks/useBrainConfig"; import { useBrainConfig } from "@/lib/context/BrainConfigProvider/hooks/useBrainConfig";
import { useSupabase } from "../context/SupabaseProvider"; import { useSupabase } from "@/lib/context/SupabaseProvider";
const axiosInstance = axios.create({ const axiosInstance = axios.create({
baseURL: `${process.env.NEXT_PUBLIC_BACKEND_URL ?? ""}`, baseURL: `${process.env.NEXT_PUBLIC_BACKEND_URL ?? ""}`,

View File

@ -1,7 +1,8 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useSupabase } from "@/lib/context/SupabaseProvider";
import { useBrainConfig } from "../context/BrainConfigProvider/hooks/useBrainConfig"; import { useBrainConfig } from "../context/BrainConfigProvider/hooks/useBrainConfig";
import { useSupabase } from "../context/SupabaseProvider";
interface FetchInstance { interface FetchInstance {
get: (url: string, headers?: HeadersInit) => Promise<Response>; get: (url: string, headers?: HeadersInit) => Promise<Response>;