모차 Cheatsheet¶
모차 - 단순, 유연한, 재미있는 자바 스크립트 테스트
Mocha는 Node.js에서 실행되는 기능 풍부한 JavaScript 테스트 프레임 워크이며 브라우저에서 비동기 테스트를 간단하고 재미있게 만듭니다. Mocha 테스트는 연속적으로 실행되며 유연한 정확한 보고를 허용하며 올바른 테스트 케이스에 익숙하지 않은 예외를 맵핑합니다.
본문 바로가기¶
설치하기¶
기본 설치¶
카지노사이트
프로젝트 설정¶
카지노사이트
패키지.json 제품 설명¶
카지노사이트
디렉토리 구조¶
카지노사이트
시작하기¶
첫 번째 시험¶
카지노사이트
카지노사이트
시험 실행¶
카지노사이트
기본 시험 Syntax¶
카지노사이트
시험 구조¶
블록 설명¶
카지노사이트
Nested 설명¶
카지노사이트
시험기관¶
ο 회원 관리
시험 Context¶
카지노사이트
훅¶
기본 Hooks¶
카지노사이트
Async 걸이¶
카지노사이트
걸이 Inheritance¶
카지노사이트
상태 걸이¶
카지노사이트
관련 기사¶
Chai 지원¶
카지노사이트
회사 소개¶
카지노사이트
본문 바로가기¶
카지노사이트
Assert Style 지원¶
오프화이트
Async 테스트¶
회사 소개¶
카지노사이트
콜백¶
오프화이트
계정 정보¶
카지노사이트
이름 *¶
카지노사이트
제품 설명¶
Mocha 구성 파일¶
카지노사이트
· 제품 설명¶
카지노사이트
Setup 파일¶
카지노사이트
환경 변수¶
카지노사이트
다중 구성¶
```javascript // mocha.config.js const baseConfig = { timeout: 5000, recursive: true, exit: true };
const configs = { unit: { ...baseConfig, spec: 'test/unit/**/*.test.js', reporter: 'spec' },
integration: { ...baseConfig, spec: 'test/integration/**/*.test.js', timeout: 10000, reporter: 'json' },
e2e: { ...baseConfig, spec: 'test/e2e/**/*.test.js', timeout: 30000, reporter: 'tap' } };
module.exports = configs[process.env.TEST_TYPE] || configs.unit; ```의 경우
공지사항¶
내장 Reporters¶
```bash
Spec reporter (default)¶
npx mocha --reporter spec
JSON reporter¶
npx mocha --reporter json
TAP reporter¶
npx mocha --reporter tap
Dot reporter¶
npx mocha --reporter dot
Progress reporter¶
npx mocha --reporter progress
Min reporter¶
npx mocha --reporter min
Landing reporter¶
npx mocha --reporter landing
List reporter¶
npx mocha --reporter list ```에 대하여
주문 Reporter¶
```javascript // reporters/custom-reporter.js function CustomReporter(runner) { const stats = runner.stats;
runner.on('start', function() { console.log('🚀 Starting test run...'); });
runner.on('suite', function(suite) {
if (suite.root) return;
console.log(📁 ${suite.title});
});
runner.on('test', function(test) {
console.log(▶️ ${test.title});
});
runner.on('pass', function(test) {
console.log(✅ ${test.title} (${test.duration}ms));
});
runner.on('fail', function(test, err) {
console.log(❌ ${test.title});
console.log(${err.message});
});
runner.on('end', function() {
console.log(🏁 ${stats.passes} passed, ${stats.failures} failed);
});
}
module.exports = CustomReporter;
// Usage // npx mocha --reporter ./reporters/custom-reporter.js ```의 경우
파일 출력을 가진 Reporter¶
```javascript // reporters/file-reporter.js const fs = require('fs'); const path = require('path');
function FileReporter(runner, options) { const reportPath = options.reporterOptions?.output || 'test-results.json'; const results = { stats: {}, tests: [], failures: [] };
runner.on('start', function() { results.stats.start = new Date(); });
runner.on('pass', function(test) { results.tests.push({ title: test.title, fullTitle: test.fullTitle(), duration: test.duration, state: 'passed' }); });
runner.on('fail', function(test, err) { results.tests.push({ title: test.title, fullTitle: test.fullTitle(), duration: test.duration, state: 'failed', error: err.message });
results.failures.push({
title: test.fullTitle(),
error: err.message,
stack: err.stack
});
});
runner.on('end', function() { results.stats.end = new Date(); results.stats.duration = results.stats.end - results.stats.start; results.stats.passes = runner.stats.passes; results.stats.failures = runner.stats.failures;
fs.writeFileSync(reportPath, JSON.stringify(results, null, 2));
console.log(`Report written to ${reportPath}`);
}); }
module.exports = FileReporter; ```에 대하여
다수 Reporters¶
```bash
Install multi-reporter¶
npm install --save-dev mocha-multi-reporters
Configuration file¶
multi-reporter-config.json¶
{ "reporterEnabled": "spec,json,tap", "jsonReporterOptions": { "output": "test-results.json" }, "tapReporterOptions": { "output": "test-results.tap" } }
Run with multiple reporters¶
npx mocha --reporter mocha-multi-reporters --reporter-options configFile=multi-reporter-config.json ```의 경우
관련 기사¶
브라우저 설정¶
카지노사이트
브라우저 테스트 파일¶
카지노사이트
Webpack 통합¶
카지노사이트
Puppeteer 통합¶
카지노사이트
뚱 베어¶
Sinon 통합¶
카지노사이트
HTTP 매킹¶
카지노사이트
모듈 Mocking¶
```javascript const proxyquire = require('proxyquire'); const { expect } = require('chai');
describe('Module Mocking', function() { it('should mock required modules', function() { const dbMock = { findUser: sinon.stub().returns({ id: 1, name: 'John' }) };
const UserService = proxyquire('../lib/user-service', {
'./database': dbMock
});
const user = UserService.getUser(1);
expect(user.name).to.equal('John');
expect(dbMock.findUser.calledWith(1)).to.be.true;
});
it('should mock with multiple dependencies', function() { const mocks = { './database': { connect: sinon.stub(), query: sinon.stub().returns([]) }, './logger': { log: sinon.stub(), error: sinon.stub() } };
const Service = proxyquire('../lib/service', mocks);
Service.initialize();
expect(mocks['./database'].connect.called).to.be.true;
expect(mocks['./logger'].log.called).to.be.true;
}); }); ```의 경우
고급 기능¶
공급 능력¶
```bash
Install parallel testing¶
npm install --save-dev mocha-parallel-tests
Run tests in parallel¶
npx mocha-parallel-tests
Specify max parallel processes¶
npx mocha-parallel-tests --max-parallel 4 ```의 경우
시험 필터링¶
카지노사이트
```javascript // Tag tests with comments describe('Calculator', function() { it('should add quickly @fast', function() { // Fast test });
it('should handle complex calculations @slow', function() { // Slow test }); }); ```의 경우
동적 시험 발생¶
```javascript describe('Dynamic Tests', function() { const testCases = [ { input: [2, 3], expected: 5 }, { input: [5, 7], expected: 12 }, { input: [-1, 1], expected: 0 }, { input: [0, 0], expected: 0 } ];
testCases.forEach(({ input, expected }) => {
it(should add ${input[0]} + ${input[1]} = ${expected}, function() {
expect(add(input[0], input[1])).to.equal(expected);
});
});
});
// Async dynamic tests describe('API Endpoints', function() { let endpoints;
before(async function() { endpoints = await loadEndpointsConfig(); });
function createEndpointTest(endpoint) {
it(should respond to ${endpoint.method} ${endpoint.path}, async function() {
const response = await request(app)
endpoint.method.toLowerCase();
expect(response.status).to.equal(endpoint.expectedStatus);
});
}
// Generate tests after loading config before(function() { endpoints.forEach(createEndpointTest); }); }); ```를 호출합니다.
시험 유틸리티¶
```javascript // test/helpers/utils.js const { expect } = require('chai');
function expectAsync(promise) {
return {
toResolve: async () => {
try {
const result = await promise;
return result;
} catch (error) {
throw new Error(Expected promise to resolve, but it rejected with: ${error.message});
}
},
toReject: async (expectedError) => {
try {
await promise;
throw new Error('Expected promise to reject, but it resolved');
} catch (error) {
if (expectedError) {
expect(error.message).to.include(expectedError);
}
return error;
}
}
}; }
function createUser(overrides = {}) { return { id: Math.floor(Math.random() * 1000), name: 'Test User', email: 'test@example.com', ...overrides }; }
module.exports = { expectAsync, createUser }; ```의 경우
시험 Data Factories¶
```javascript // test/factories/user-factory.js class UserFactory { static create(overrides = {}) { return { id: this.generateId(), name: 'John Doe', email: 'john@example.com', age: 30, active: true, createdAt: new Date(), ...overrides }; }
static createMany(count, overrides = {}) { return Array.from({ length: count }, (_, index) => this.create({ id: index + 1, ...overrides }) ); }
static generateId() { return Math.floor(Math.random() * 10000); } }
module.exports = UserFactory;
// Usage in tests const UserFactory = require('./factories/user-factory');
describe('User Service', function() { it('should process user', function() { const user = UserFactory.create({ name: 'Jane' }); const result = processUser(user); expect(result.displayName).to.equal('Jane'); });
it('should handle multiple users', function() { const users = UserFactory.createMany(5); expect(users).to.have.length(5); }); }); ```로
플러그인¶
인기 플러그인¶
카지노사이트
Chai Plugins 사용법¶
오프화이트
사용자 정의 플러그인 개발¶
카지노사이트
CI/CD 통합¶
GitHub 작업¶
__CODE_BLOCK_49_로그
Jenkins 파이프 라인¶
카지노사이트
Docker 통합¶
```dockerfile
Dockerfile.test¶
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./ RUN npm ci
COPY . .
CMD ["npm", "test"] ```를 호출합니다.
```yaml
docker-compose.test.yml¶
version: '3.8' services: test: build: context: . dockerfile: Dockerfile.test environment: - NODE_ENV=test volumes: - ./coverage:/app/coverage ```의 경우
최고의 연습¶
시험기관¶
카지노사이트
Test Data 관리¶
카지노사이트
Async 모범 사례¶
```javascript // Good: Proper async handling describe('Async Tests', function() { it('should handle promises', async function() { const result = await asyncOperation(); expect(result).to.exist; });
it('should handle errors', async function() { await expect(failingOperation()).to.be.rejected; }); });
// Good: Proper timeout handling describe('Slow Tests', function() { this.timeout(10000);
it('should complete slow operation', async function() { const result = await slowOperation(); expect(result).to.exist; }); }); ```로
관련 링크¶
Debug 모드¶
카지노사이트
시험 Debugging¶
카지노사이트
오류 Debugging¶
카지노사이트
- 연혁¶
시험 성과¶
```javascript // Optimize test setup describe('Performance Tests', function() { // Use before/after for expensive setup before(async function() { this.database = await setupDatabase(); });
after(async function() { await this.database.close(); });
// Avoid unnecessary work in tests it('should be fast', function() { // Minimal test implementation expect(true).to.be.true; }); }); ```에
병렬 실행¶
```bash
Run tests in parallel¶
npx mocha-parallel-tests
Specify parallel workers¶
npx mocha-parallel-tests --max-parallel 4 ```의 경우
메모리 최적화¶
카지노사이트
문제 해결¶
일반적인 문제¶
카지노사이트
Debug 구성¶
```javascript // Debug configuration issues console.log('Mocha config:', JSON.stringify(require('./.mocharc.json'), null, 2));
// Debug test discovery npx mocha --dry-run
// Debug reporter issues npx mocha --reporter json > test-results.json ```의 경우
제품정보¶
Mocha는 다음과 같은 유연한 강력한 JavaScript 테스트 프레임 워크입니다.
- Flexible Structure: BDD, TDD 및 사용자 지정 인터페이스 지원
- Async Support: 약속, 콜백 및 async/await에 대한 기본 지원
- Rich Ecosystem: 광범위한 플러그인 생태계 및 통합
- Multiple Environments: Node.js 및 브라우저에서 실행
- ** 효과적인 보고 **: 다수 붙박이 보고자 및 주문 보고자 지원
- ** 고급 기능**: 병렬 테스트, 테스트 필터링 및 동적 테스트 생성
- CI/CD 준비: 연속 통합 시스템과 우수한 통합
- Debugging Support: 풍부한 디버깅 기능 및 오류 보고
Mocha는 유연성, 광범위한 기능 세트 및 성숙한 생태계를 사용하여 JavaScript 테스트를 위한 견고한 기반을 제공합니다. 탁월한 개발자 경험 및 신뢰할 수 있는 테스트 실행을 유지하면서 팀의 특정 요구 사항에 맞는 테스트 워크플로를 구축할 수 있습니다.
<문서> 기능 copyToClipboard () 이름 * const 명령어 = document.querySelectorAll('code'); let allCommands = ''; 명령. forEach(cmd =>의 경우 모든Commands +=cmd.textContent + navigator.clipboard.write텍스(allCommands); alert('모든 명령은 클립보드에 복사!'); 이름 *
함수 생성PDF() { 창. 인쇄 (); 이름 *