Skip to content

Commit

Permalink
test: workbook landing page test
Browse files Browse the repository at this point in the history
  • Loading branch information
soomin9106 committed Jun 13, 2024
1 parent 8d94644 commit 8f27b07
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 45 deletions.
5 changes: 4 additions & 1 deletion src/app/workbook/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default function WorkbookPage() {
const pathname = usePathname();
const workbookId = getWorkbookId(pathname);

const { data: workbookInfo, isError } = useQuery({
const { data: workbookInfo, isLoading, isError } = useQuery({
...getWorkbookQueryOptions(Number(workbookId)),
});

Expand All @@ -47,6 +47,9 @@ export default function WorkbookPage() {
setIsClient(true);
}, []);

if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error loading workbook</div>;

return (
<main className="flex h-[100vh] w-full flex-col items-center overflow-x-hidden">
<div className="flex h-full w-full max-w-screen-sm flex-col space-y-[24px] overflow-y-scroll">
Expand Down
98 changes: 56 additions & 42 deletions src/app/workbook/workbookpage.test.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, screen, waitFor, renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
import { HttpResponse, http } from 'msw';
import { apiRoutes } from '@shared/constants/apiRoutes';
import { expect, vi, describe, it, beforeAll, afterEach, afterAll } from 'vitest';
import { expect, vi, describe, it, beforeAll, afterEach, afterAll, beforeEach } from 'vitest';
import { server } from '@mocks/server';
import WorkbookPage from './[id]/page';
import { JSX, ClassAttributes, ImgHTMLAttributes } from 'react';
import { JSX, ClassAttributes, ImgHTMLAttributes, ReactNode } from 'react';
import response from '@mocks/response';
import { getWorkbookQueryOptions, useWorkbook } from '@workbook/remotes/getWorkbookQueryOptions';

export const createQueryProviderWrapper = () => {
const queryClient = new QueryClient();
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
};

// TBD: 필요하면 vitest.setup.ts 에 빼놓기
vi.mock('next/navigation', () => ({
Expand All @@ -15,7 +26,7 @@ vi.mock('next/navigation', () => ({
return null;
},
}),
usePathname: () => '/workbook/1',
usePathname: () => '/workbooks/1',
}));

vi.mock('next/image', () => ({
Expand All @@ -25,50 +36,53 @@ vi.mock('next/image', () => ({
},
}));

vi.mock('/public/assets/icon36/share_36.svg', () => ({ __esModule: true, default: '' }));
vi.mock('/public/assets/icon36/*', () => ({ __esModule: true, default: '' }));
vi.mock('/public/assets/*', () => ({ __esModule: true, default: '' }));

const queryClient = new QueryClient();
describe('워크북 페이지 테스트', () => {
it('workbook page 랜딩 시 react-query 테스트', async () => {
const { result } = renderHook(() => useWorkbook(1), {
wrapper: createQueryProviderWrapper(),
});

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
await waitFor(() => {
expect(result.current.data?.title).toBe('재태크, 투자 필수 용어 모음집');
expect(result.current.data?.mainImageUrl).toBe('/main_img.png');
expect(result.current.data?.description).toBe('사회 초년생부터, 직장인, 은퇴자까지 모두가 알아야 할 기본적인 재태크, 투자 필수 용어 모음집 입니다.');
expect(result.current.data?.category).toBe('경제');
})
});

describe('워크북 페이지 테스트', () => {
it('데이터와 함께 워크북 페이지를 로딩한다', async () => {
await waitFor(async () => {
render(
<QueryClientProvider client={queryClient}>
<WorkbookPage />
</QueryClientProvider>
);
});
const queryClient = new QueryClient();
render(
<QueryClientProvider client={queryClient}>
<WorkbookPage />
</QueryClientProvider>
);

// await waitFor(() => {
// expect(screen.getByText('재태크, 투자 필수 용어 모음집')).toBeInTheDocument();
// expect(screen.getByText('사회 초년생부터, 직장인, 은퇴자까지 모두가 알아야 할 기본적인 재태크, 투자 필수 용어 모음집 입니다.')).toBeInTheDocument();
// expect(screen.getByText('ISA(개인종합자산관리계좌)란?')).toBeInTheDocument();
// });
await waitFor(() => {
expect(screen.getByText('재태크, 투자 필수 용어 모음집')).toBeInTheDocument();
expect(screen.getByAltText('Workbook landing image')).toHaveAttribute('src', '/main_img.png');
expect(screen.getByText('사회 초년생부터, 직장인, 은퇴자까지 모두가 알아야 할 기본적인 재태크, 투자 필수 용어 모음집 입니다.')).toBeInTheDocument();
});
});

it('데이터 패칭에 실패 했을 때 에러 메시지를 보여준다', async () => {
// server.use(
// http.get(apiRoutes.workbook.replace(':workbookId', '1'), ({ request }) => {
// return new HttpResponse(null, { status: 404 });
// })
// );
/** 데이터가 잘 불러와지고 있는 듯? */
// it('데이터 패칭에 실패 했을 때 에러 메시지를 보여준다', async () => {
// const queryClient = new QueryClient();
// server.use(
// http.get(apiRoutes.workbook.replace(':workbookId', '1'), ({ request }) => {
// return new HttpResponse(null, { status: 500 });
// })
// );

// await waitFor(async () => {
// render(
// <QueryClientProvider client={queryClient}>
// <WorkbookPage />
// </QueryClientProvider>
// );
// });
// render(
// <QueryClientProvider client={queryClient}>
// <WorkbookPage />
// </QueryClientProvider>
// );

// await waitFor(() => {
// expect(screen.getByText(/Error/)).toBeInTheDocument();
// });
});
// await waitFor(() => {
// expect(screen.getByText('Error loading workbook')).toBeInTheDocument();
// });
// });
});
14 changes: 13 additions & 1 deletion src/workbook/remotes/getWorkbookQueryOptions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { UseQueryOptions } from "@tanstack/react-query";
import { UseQueryOptions, useQuery } from "@tanstack/react-query";

import { ApiResponse, axiosRequest } from "@api/api-config";

Expand Down Expand Up @@ -27,3 +27,15 @@ export const getWorkbookQueryOptions = (
select: (data) => data.data,
};
};

export const useWorkbook = (workbookId: number) => {
return useQuery({
queryKey: ['workbook', workbookId],
queryFn: async () => {
console.log('Fetching workbook data...');
const response = await axiosRequest<ApiResponse<WorkbookInfo>>("get", apiRoutes.workbook.replace(':workbookId', workbookId.toString()));
console.log('Fetched data:', response.data);
return response.data;
},
});
};;
12 changes: 11 additions & 1 deletion vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,17 @@ const resolve = (path: string) => pathResolve(__dirname, path);
import svgr from 'vite-plugin-svgr';

export default defineConfig({
plugins: [react(), svgr()],
plugins: [
react(),
svgr({
svgrOptions: {
ref: true,
svgo: false,
titleProp: true,
},
include: "**/*.svg",
}),
],
test: {
globals: true,
environment: "jsdom",
Expand Down

0 comments on commit 8f27b07

Please sign in to comment.