인기 카테고리¶
Jest - 기쁨 자바 스크립트 테스트
Jest는 단순성에 초점을 맞춘 즐거운 JavaScript 테스트 프레임 워크입니다. 그것은 대부분의 JavaScript 프로젝트에 대한 상자에서 작동하고 스냅 샷 테스트, 내장 테스트 런너, assertion 라이브러리 및 강력한 조깅 기능과 같은 기능을 제공합니다.
본문 바로가기¶
- 설치
- 시작
- 기본 테스트
- Matchers
- Async 테스트
- 마킹
- Snapshot 테스트
- 구성
- 리터 테스트
- 코드 적용
- 고급 기능
- 테스트 패턴
- 공연
- 입사
- Troubleshooting
- 모범 사례
설치하기¶
기본 설치¶
카지노사이트
React 프로젝트¶
카지노사이트
패키지.json 제품 설명¶
카지노사이트
프로젝트 구조¶
카지노사이트
시작하기¶
첫 번째 시험¶
카지노사이트
카지노사이트
시험 실행¶
카지노사이트
시험기관¶
카지노사이트
기본 테스트¶
시험 구조¶
카지노사이트
설치 및 경고¶
카지노사이트
Skipping 및 집중 시험¶
ο 회원 관리
모수 시험¶
카지노사이트
관련 기사¶
기본 일치¶
카지노사이트
문자열 일치¶
카지노사이트
배열과 목표 일치¶
카지노사이트
예외 일치¶
카지노사이트
주문 일치¶
카지노사이트
Async 테스트¶
회사 소개¶
카지노사이트
콜백¶
카지노사이트
타이머 및 지연¶
오프화이트
뚱 베어¶
기능 Mocking¶
카지노사이트
모듈 Mocking¶
오프화이트
부분적인 Mocking¶
카지노사이트
스파이 기능¶
카지노사이트
Mock 파일¶
카지노사이트
Snapshot 테스트¶
기본 Snapshots¶
카지노사이트
인라인 Snapshots¶
카지노사이트
사용자 정의 스냅 샷 serializers¶
카지노사이트
재산 Matchers¶
```javascript describe('Property matchers', () => { test('should match snapshot with dynamic values', () => { const user = { id: Math.random(), name: 'John', createdAt: new Date(), profile: { lastLogin: new Date(), sessionId: 'abc123' } };
expect(user).toMatchSnapshot({
id: expect.any(Number),
createdAt: expect.any(Date),
profile: {
lastLogin: expect.any(Date),
sessionId: expect.any(String)
}
});
}); }); ```의 경우
제품 설명¶
Jest 구성 파일 형식¶
```javascript // jest.config.js module.exports = { // Test environment testEnvironment: 'jsdom', // 'node' | 'jsdom'
// Test file patterns testMatch: [ '/tests//.(js|jsx|ts|tsx)', '**/.(test|spec).(js|jsx|ts|tsx)' ],
// Setup files
setupFilesAfterEnv: ['
// Module name mapping
moduleNameMapping: {
'^@/(.*)\(': '<rootDir>/src/\)1',
'\.(css|less|scss|sass)\(': 'identity-obj-proxy',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)\)': '
// Transform files
transform: {
'^.+\.(js|jsx|ts|tsx)\(': 'babel-jest',
'^.+\\.css\)': '
// Coverage collectCoverageFrom: [ 'src//*.{js,jsx,ts,tsx}', '!src//*.d.ts', '!src/index.js', '!src/serviceWorker.js' ],
coverageThreshold: { global: { branches: 80, functions: 80, lines: 80, statements: 80 } },
// Ignore patterns testPathIgnorePatterns: [ '/node_modules/', '/build/', '/dist/' ],
// Module directories
moduleDirectories: ['node_modules', '
// Globals globals: { 'ts-jest': { tsconfig: 'tsconfig.json' } } }; ```에 대하여
TypeScript 구성¶
```javascript // jest.config.js for TypeScript module.exports = { preset: 'ts-jest', testEnvironment: 'jsdom',
moduleNameMapping: { '^@/(.*)\(': '<rootDir>/src/\)1' },
setupFilesAfterEnv: ['
transform: { '^.+\.tsx?$': 'ts-jest' },
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
globals: { 'ts-jest': { tsconfig: { jsx: 'react-jsx' } } } }; ```의 경우
설정 파일¶
```javascript // src/setupTests.js import '@testing-library/jest-dom';
// Mock IntersectionObserver global.IntersectionObserver = class IntersectionObserver { constructor() {} disconnect() {} observe() {} unobserve() {} };
// Mock matchMedia Object.defineProperty(window, 'matchMedia', { writable: true, value: jest.fn().mockImplementation(query => ({ matches: false, media: query, onchange: null, addListener: jest.fn(), removeListener: jest.fn(), addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(), })), });
// Global test utilities global.testUtils = { createMockUser: () => ({ id: 1, name: 'Test User', email: 'test@example.com' }) }; ```에 대하여
환경 변수¶
```javascript
// jest.config.js
module.exports = {
setupFiles: ['
// config/jest/setEnvVars.js process.env.NODE_ENV = 'test'; process.env.API_URL = 'http://localhost:3001'; process.env.FEATURE_FLAG_NEW_UI = 'true'; ```의 경우
React 테스트¶
구성 요소 테스트¶
카지노사이트
이벤트 테스트¶
카지노사이트
Hook 테스트¶
카지노사이트
부호 적용¶
적용 구성¶
카지노사이트
적용 스크립트¶
카지노사이트
Ignoring 적용¶
카지노사이트
고급 기능¶
주문 시험 환경¶
```javascript // jest-environment-custom.js const { TestEnvironment } = require('jest-environment-jsdom');
class CustomTestEnvironment extends TestEnvironment { constructor(config, context) { super(config, context);
// Add custom globals
this.global.customGlobal = 'test-value';
}
async setup() { await super.setup();
// Custom setup logic
this.global.mockDatabase = {
users: [],
addUser: (user) => this.global.mockDatabase.users.push(user),
getUser: (id) => this.global.mockDatabase.users.find(u => u.id === id)
};
}
async teardown() { // Custom teardown logic this.global.mockDatabase = null;
await super.teardown();
} }
module.exports = CustomTestEnvironment;
// jest.config.js module.exports = { testEnvironment: './jest-environment-custom.js' }; ```의 경우
회사 소개¶
```javascript // custom-reporter.js class CustomReporter { constructor(globalConfig, options) { this._globalConfig = globalConfig; this._options = options; }
onRunStart(results, options) { console.log('🚀 Starting test run...'); }
onTestStart(test) {
console.log(▶️ Running ${test.path});
}
onTestResult(test, testResult, aggregatedResult) {
if (testResult.numFailingTests > 0) {
console.log(❌ ${test.path} - ${testResult.numFailingTests} failed);
} else {
console.log(✅ ${test.path} - all tests passed);
}
}
onRunComplete(contexts, results) {
console.log(🏁 Test run complete: ${results.numPassedTests} passed, ${results.numFailedTests} failed);
}
}
module.exports = CustomReporter;
// jest.config.js module.exports = { reporters: [ 'default', ['./custom-reporter.js', { option1: 'value1' }] ] }; ```의 경우
글로벌 설정 및 Teardown¶
카지노사이트
플러그인 보기¶
```javascript // watch-plugin-custom.js class CustomWatchPlugin { constructor({ stdin, stdout, config, testPathPattern }) { this._stdin = stdin; this._stdout = stdout; this._config = config; this._testPathPattern = testPathPattern; }
apply(jestHooks) { jestHooks.onFileChange(({ projects }) => { console.log('📁 Files changed, running tests...'); }); }
getUsageInfo() { return { key: 'c', prompt: 'clear console' }; }
run(globalConfig, updateConfigAndRun) { console.clear(); return Promise.resolve(); } }
module.exports = CustomWatchPlugin;
// jest.config.js module.exports = { watchPlugins: [ 'jest-watch-typeahead/filename', 'jest-watch-typeahead/testname', './watch-plugin-custom.js' ] }; ```의 경우
테스트 패턴¶
페이지 개체 모델¶
```javascript // pageObjects/LoginPage.js export class LoginPage { constructor(page) { this.page = page; }
get emailInput() { return this.page.getByLabelText(/email/i); }
get passwordInput() { return this.page.getByLabelText(/password/i); }
get submitButton() { return this.page.getByRole('button', { name: /login/i }); }
get errorMessage() { return this.page.getByTestId('error-message'); }
async login(email, password) { await this.emailInput.fill(email); await this.passwordInput.fill(password); await this.submitButton.click(); }
async expectErrorMessage(message) { await expect(this.errorMessage).toHaveText(message); } }
// Login.test.js import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { LoginPage } from './pageObjects/LoginPage'; import { Login } from './Login';
describe('Login', () => {
test('should display error for invalid credentials', async () => {
const user = userEvent.setup();
render(
const loginPage = new LoginPage(screen);
await loginPage.login('invalid@email.com', 'wrongpassword');
await loginPage.expectErrorMessage('Invalid credentials');
}); }); ```를 호출합니다.
시험 Factories¶
```javascript // factories/userFactory.js export const createUser = (overrides = {}) => ({ id: Math.floor(Math.random() * 1000), name: 'John Doe', email: 'john@example.com', age: 30, isActive: true, createdAt: new Date(), ...overrides });
export const createUsers = (count, overrides = {}) => Array.from({ length: count }, (_, index) => createUser({ id: index + 1, ...overrides }) );
// Usage in tests import { createUser, createUsers } from './factories/userFactory';
describe('User Service', () => { test('should process user data', () => { const user = createUser({ name: 'Jane Doe', age: 25 });
const result = processUser(user);
expect(result.displayName).toBe('Jane Doe (25)');
});
test('should handle multiple users', () => { const users = createUsers(5, { isActive: true });
const activeUsers = filterActiveUsers(users);
expect(activeUsers).toHaveLength(5);
}); }); ```의 경우
시험 유틸리티¶
```javascript // testUtils/renderWithProviders.js import React from 'react'; import { render } from '@testing-library/react'; import { BrowserRouter } from 'react-router-dom'; import { QueryClient, QueryClientProvider } from 'react-query'; import { ThemeProvider } from 'styled-components'; import { theme } from '../src/theme';
export function renderWithProviders(
ui,
{
initialEntries = ['/'],
queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false }
}
}),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return (
return render(ui, { wrapper: Wrapper, ...renderOptions }); }
// Usage import { renderWithProviders } from './testUtils/renderWithProviders';
test('should render with all providers', () => {
renderWithProviders(
도메인 Logic에 대한 사용자 정의 일치¶
카지노사이트
- 연혁¶
시험 성능 최적화¶
오프화이트
선택적 시험 실행¶
카지노사이트
메모리 최적화¶
__CODE_BLOCK_49_로그
통합¶
CI/CD 통합¶
카지노사이트
Docker 통합¶
```dockerfile
Dockerfile.test¶
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./ RUN npm ci
COPY . .
CMD ["npm", "test", "--", "--ci", "--coverage", "--watchAll=false"] ```를 호출합니다.
IDE 통합¶
json
// .vscode/settings.json
{
"jest.jestCommandLine": "npm test --",
"jest.autoRun": {
"watch": true,
"onStartup": ["all-tests"]
},
"jest.showCoverageOnLoad": true,
"jest.coverageFormatter": "DefaultFormatter",
"jest.debugMode": true
}의 경우
문제 해결¶
일반적인 문제¶
카지노사이트
Debugging 시험¶
카지노사이트
Mock 문제¶
```javascript // Reset mocks between tests beforeEach(() => { jest.clearAllMocks(); jest.resetAllMocks(); jest.restoreAllMocks(); });
// Mock implementation issues const mockFn = jest.fn(); mockFn.mockImplementation(() => { throw new Error('Mock error'); });
// Module mock issues jest.mock('./module', () => ({ __esModule: true, default: jest.fn(), namedExport: jest.fn() })); ```로
최고의 연습¶
시험기관¶
- 증명서: 명확한, descriptive 시험 이름 사용
- Arrange-Act-Assert: AAA 패턴을 따르십시오.
- ** 단 하나 책임 **: 가능한 한 테스트 당 하나의 assertion
- ** 테스트 구조 **:
describe블록과 그룹 관련 테스트
시험 질¶
- **Edge 케이스 **: 시험 경계 상태 및 가장자리 상자
- ** 수수료**: 시험 오류 시나리오 및 예외
- Async Code: Properly 테스트 비동기 작업
- Mocking Strategy: Mock 외부 의존성
- 연혁¶
- ** 선택 실행 **: 시계 모드 및 선택 테스트 실행
- Parallel Execution: Jest의 병렬 실행
- Cache 최적화: Jest의 캐싱을 효과적으로 사용하십시오.
- ** 메모리 관리 **: 자원을 청소하고 조롱
- 연혁¶
- Regular Update: 최신 및 테스트 라이브러리 업데이트 유지
- Coverage Goals: 적절한 적용 임계값 설정 및 유지
- Test Documentation: 문서 복합 시험 시나리오
- Refactoring: 생산 코드와 함께 Refactor 테스트
제품정보¶
Jest는 제공하는 포괄적 인 JavaScript 테스트 프레임 워크입니다.
- Zero 구성: 대부분의 프로젝트에 대한 상자에서 작동합니다.
- ** 강력한 매커 **: Extensive assertion library with custom matcher 지원
- Mocking Capabilities: 기능, 모듈 및 타이머를 위한 내장
- Snapshot Testing: UI 컴포넌트의 비주얼 회귀 테스트
- Code Coverage: 임계값 강제로 보고하는 내장 적용
- **패럴 실행 **: worker 프로세스로 빠른 테스트 실행
- ** 배치 모드**: 자동 시험 re-running를 가진 상호 작용하는 발달
- Extensive Ecosystem: 플러그인 및 통합의 풍부한 생태계
React 애플리케이션, Node.js 백엔드 및 일반 JavaScript 코드를 테스트하는 Jest 엑셀. 개발자 경험, 종합 기능 세트 및 우수한 문서에 대한 초점은 현대 개발 워크플로우에서 JavaScript 테스트에 대한 선택입니다.
<문서> 기능 copyToClipboard () 이름 * const 명령어 = document.querySelectorAll('code'); let allCommands = ''; 명령. forEach(cmd =>의 경우 모든Commands +=cmd.textContent + navigator.clipboard.write텍스(allCommands); alert('모든 명령은 클립보드에 복사!'); 이름 *
함수 생성PDF() { 창. 인쇄 (); 이름 *