1. 설치
pnpm add -D @testing-library/dom @testing-library/jest-dom @testing-library/react @testing-library/user-event @types/jest jest jest-environment-jsdom msw
pnpm create jest@latest
2. jest.config 설정
import type { Config } from 'jest';
import nextJest from 'next/jest.js';
const createJestConfig = nextJest({
dir: './',
});
const config: Config = {
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while
// executing the test
collectCoverage: true,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',
// A map from regular expressions to module names or to arrays of module names
// that allow to stub out resources with a single module
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
// The test environment that will be used for testing
testEnvironment: 'jsdom',
// The glob patterns Jest uses to detect test files
testMatch: ['**/*.test.(ts|tsx)'],
};
export default createJestConfig(config);
3. Mock Query Client 설정
import { QueryClient } from '@tanstack/react-query';
const createTestQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Infinity,
},
},
});
const testQueryClient = createTestQueryClient();
4. Mock Router 설정
import '@testing-library/jest-dom';
const createRouter = () => ({
push: jest.fn(),
replace: jest.fn(),
back: jest.fn(),
forward: jest.fn(),
refresh: jest.fn(),
prefetch: jest.fn(),
});
export const router = createRouter();
5. Render 잘 되는지 기본 테스트
만약 테스트할 컴포넌트가 SignInForm 이라면 아래처럼...
import '@testing-library/jest-dom';
import { render } from '@testing-library/react';
describe('SignIn', () => {
const renderWithRouterAndQueryClient = () =>
render(
<AppRouterContext.Provider value={{ ...router }}>
<QueryClientProvider client={testQueryClient}>
<SignInForm />
</QueryClientProvider>
</AppRouterContext.Provider>,
);
it('renders correctly', () => {
renderWithRouterAndQueryClient();
});
});
'TIL' 카테고리의 다른 글
[241220 TIL] 기본적인 husky 세팅 (1) | 2024.12.20 |
---|---|
[241219 TIL] Severless (0) | 2024.12.19 |
[241219 TIL] pnpm 장점 (0) | 2024.12.19 |
[241219 TIL] Framer-motion 기초 (0) | 2024.12.19 |
[241209 TIL] AWS - RDS, EB 에 nest 배포(3) (0) | 2024.12.09 |