Skip to content

Commit

Permalink
Chat 생성 및 Chat Session 확인 테스트 스크립트 작성
Browse files Browse the repository at this point in the history
  • Loading branch information
Lee-Dongwook committed Oct 28, 2024
1 parent 6771e71 commit 15f943f
Show file tree
Hide file tree
Showing 3 changed files with 241 additions and 0 deletions.
79 changes: 79 additions & 0 deletions src/hooks/test/useChatSessions.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { renderHook, waitFor } from '@testing-library/react';
import { useChatSessions } from '@/hooks/useChatSessions';
import { getDocs } from 'firebase/firestore';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

jest.mock('firebase/firestore', () => ({
getDocs: jest.fn(),
query: jest.fn(),
where: jest.fn(),
collection: jest.fn(),
}));

const createTestQueryClient = () => {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
};

const wrapper = ({ children }: { children: React.ReactNode }) => {
return (
<QueryClientProvider client={createTestQueryClient()}>
{children}
</QueryClientProvider>
);
};

describe('useChatSessions 테스트', () => {
const mockUserId = 'user123';

it('성공적으로 세션 목록을 가져와야 한다.', async () => {
const mockSessions = [
{
id: '1',
userIds: ['user123', 'alice'],
sessionName: 'Chat with Alice',
},
{ id: '2', userIds: ['user123', 'bob'], sessionName: 'Chat with Bob' },
];

(getDocs as jest.Mock).mockResolvedValueOnce({
docs: mockSessions.map((session) => ({
id: session.id,
data: () => session,
})),
});

const { result } = renderHook(() => useChatSessions(mockUserId), {
wrapper,
});

await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(result.current.data).toEqual(mockSessions);
});

it('Firestore 호출 실패 시 에러를 반환해야 한다.', async () => {
const errorMessage = 'Failed to fetch sessions';

(getDocs as jest.Mock).mockRejectedValueOnce(new Error(errorMessage));

const { result } = renderHook(() => useChatSessions(mockUserId), {
wrapper,
});

await waitFor(() => expect(result.current.isError).toBe(true));
expect(result.current.error).toBe(new Error(errorMessage));
});

it('사용자 ID가 없을 때, 쿼리가 실행되지 않아야 한다.', async () => {
const { result } = renderHook(() => useChatSessions(''), {
wrapper,
});

expect(result.current.isPaused).toBe(true);
});
});
82 changes: 82 additions & 0 deletions src/hooks/test/useCheckUserRole.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { renderHook, waitFor } from '@testing-library/react';
import { useCheckUserRole } from '@/hooks/useCheckUserRole';
import { getDoc } from 'firebase/firestore';
import { useDispatch } from 'react-redux';
import { setUserRole } from '@/redux/slice/userSlice';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { UserRole } from '@/types';

jest.mock('firebase/firestore', () => ({
getDoc: jest.fn(),
doc: jest.fn(),
}));

jest.mock('react-redux', () => ({
useDispatch: jest.fn(),
}));

const createTestQueryClient = () => {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
};

const wrapper = ({ children }: { children: React.ReactNode }) => {
return (
<QueryClientProvider client={createTestQueryClient()}>
{children}
</QueryClientProvider>
);
};

describe('useChecUserRole 테스트', () => {
const mockUserId = 'user123';
const dispatch = jest.fn();

beforeEach(() => {
(useDispatch as unknown as jest.Mock).mockReturnValue(dispatch);
});

it('성공적으로 사용자 역할을 가져와서 Redux 상태를 업데이트 한다.', async () => {
const mockUserRole: UserRole = 'user';

(getDoc as jest.Mock).mockResolvedValueOnce({
exists: true,
data: () => ({ role: mockUserRole }),
});

const { result } = renderHook(() => useCheckUserRole(mockUserId), {
wrapper,
});

await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(result.current.data).toBe(mockUserRole);
expect(dispatch).toHaveBeenCalledWith(setUserRole(mockUserRole));
});
it('사용자 역할이 없는 경우 에러를 반환해야 한다', async () => {
const errorMessage = 'User role not found';

(getDoc as jest.Mock).mockResolvedValueOnce({
exists: () => false,
});

const { result } = renderHook(() => useCheckUserRole(mockUserId), {
wrapper,
});

await waitFor(() => expect(result.current.isError).toBe(true));
expect(result.current.error).toEqual(new Error(errorMessage));
});

it('userId가 없을 때 쿼리가 실행되지 않아야 한다', async () => {
const { result } = renderHook(() => useCheckUserRole(''), {
wrapper,
});

expect(result.current.isPaused).toBe(true);
});
});
80 changes: 80 additions & 0 deletions src/hooks/test/useCreateChat.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { renderHook, act, waitFor } from '@testing-library/react';
import { useCreateChat } from '@/hooks/useCreateChat';
import { addDoc } from 'firebase/firestore';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

jest.mock('firebase/firestore', () => ({
addDoc: jest.fn(),
collection: jest.fn(),
serverTimestamp: jest.fn(() => ({
seconds: 1628880000,
nanoseconds: 0,
})),
}));

const createTestQueryClient = () => {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
};

const wrapper = ({ children }: { children: React.ReactNode }) => {
return (
<QueryClientProvider client={createTestQueryClient()}>
{children}
</QueryClientProvider>
);
};

describe('useCreateChat 테스트', () => {
const mockSessionName = 'New Chat Session';

it('성공적으로 채팅 세션을 생성해야 한다', async () => {
const mockDocRef = { id: 'chat123' };
(addDoc as jest.Mock).mockResolvedValueOnce(mockDocRef);

const { result } = renderHook(() => useCreateChat(), {
wrapper,
});

await act(async () => {
result.current.mutate(mockSessionName);
});

await waitFor(() => expect(result.current.isSuccess).toBe(true));

expect(addDoc).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
sessionName: mockSessionName,
createdAt: expect.any(Object),
lastActivity: expect.any(Object),
})
);

expect(result.current.data).toEqual({
sessionName: mockSessionName,
createdAt: expect.any(Object),
lastActivity: expect.any(Object),
id: 'chat123',
});
});

it('채팅 세션 생성 실패 시 에러를 반환해야 한다', async () => {
const errorMessage = 'Failed to create chat session';
(addDoc as jest.Mock).mockRejectedValueOnce(new Error(errorMessage));

const { result } = renderHook(() => useCreateChat(), { wrapper });

await act(async () => {
result.current.mutate(mockSessionName);
});

await waitFor(() => expect(result.current.isError).toBe(true));
expect(result.current.error).toEqual(new Error(errorMessage));
});
});

0 comments on commit 15f943f

Please sign in to comment.