콘텐츠로 이동

Cypress 열 시트

Cypress - 종료된 테스트는 쉬운

를 만들었습니다

Cypress는 현대 웹에 내장 된 차세대 프런트 엔드 테스트 도구입니다. 그것은 현대 신청을 시험할 때 중요한 고통 점 개발자와 QA 엔지니어 얼굴을 요구합니다. Cypress는 모든 종류의 테스트를 작성할 수 있습니다. 종료 테스트, 통합 테스트, 단위 시험.

본문 바로가기

설치하기

기본 설치

카지노사이트

프로젝트 설정

카지노사이트

폴더 구조

카지노사이트

Package.json 스크립트

카지노사이트

시작하기

첫 번째 시험

카지노사이트

기본 시험 구조

카지노사이트

시험 Hooks

카지노사이트

기본 명령

- 연혁

카지노사이트

성분 상호 작용

카지노사이트

요소 쿼리

카지노사이트

회사 소개

ο 회원 관리

계정 만들기

카지노사이트

회사 소개

CSS 선택기

카지노사이트

Data Attributes (추천)

카지노사이트

XPath ( 플러그인 포함)

카지노사이트

카지노사이트

회사 소개

카지노사이트

관련 기사

자주 묻는 질문

카지노사이트

현재 위치

카지노사이트

URL 지원

오프화이트

회사 소개

카지노사이트

네트워크 테스트

자주 묻는 질문

오프화이트

자주 묻는 질문

카지노사이트

네트워크 조건

카지노사이트

다수 Intercepts

카지노사이트

파일 작업

파일 업로드

카지노사이트

파일 다운로드

카지노사이트

정착물과 일

카지노사이트

읽기 / 쓰기 파일

```javascript // Read file cy.readFile('cypress/fixtures/data.json').then((data) => { expect(data).to.have.property('users') })

// Write file cy.writeFile('cypress/fixtures/output.json', { timestamp: Date.now(), testResults: 'passed' })

// Append to file cy.writeFile('cypress/fixtures/log.txt', 'New log entry\n', { flag: 'a+' }) ```의 경우

사용자 정의 명령

기본 명령

```javascript // cypress/support/commands.js

// Simple command Cypress.Commands.add('login', (email, password) => { cy.visit('/login') cy.get('[data-cy="email"]').type(email) cy.get('[data-cy="password"]').type(password) cy.get('[data-cy="submit"]').click() })

// Command with options Cypress.Commands.add('login', (email, password, options = {}) => { const { rememberMe = false } = options

cy.visit('/login') cy.get('[data-cy="email"]').type(email) cy.get('[data-cy="password"]').type(password)

if (rememberMe) { cy.get('[data-cy="remember-me"]').check() }

cy.get('[data-cy="submit"]').click() })

// Usage cy.login('user@example.com', 'password123') cy.login('user@example.com', 'password123', { rememberMe: true }) ```에 대하여

고급 사용자 정의 명령

```javascript // Command that returns value Cypress.Commands.add('getLocalStorage', (key) => { return cy.window().then((win) => { return win.localStorage.getItem(key) }) })

// Command with chaining Cypress.Commands.add('dataCy', (value) => { return cy.get([data-cy=${value}]) })

// Usage with chaining cy.dataCy('submit-btn').click() cy.dataCy('username').type('john@example.com')

// Command with retry logic Cypress.Commands.add('waitForElement', (selector, timeout = 10000) => { cy.get(selector, { timeout }).should('be.visible') })

// API command Cypress.Commands.add('apiLogin', (email, password) => { cy.request({ method: 'POST', url: '/api/auth/login', body: { email, password } }).then((response) => { window.localStorage.setItem('authToken', response.body.token) }) }) ```의 경우

Overwriting 명령

```javascript // Overwrite existing command Cypress.Commands.overwrite('visit', (originalFn, url, options) => { const domain = Cypress.config('baseUrl')

if (domain) { const combinedUrl = ${domain}${url} return originalFn(combinedUrl, options) }

return originalFn(url, options) })

// Overwrite type command to clear first Cypress.Commands.overwrite('type', (originalFn, element, text, options) => { if (options && options.clearFirst !== false) { element.clear() }

return originalFn(element, text, options) }) ```에 대하여

TypeScript 지원

```typescript // cypress/support/commands.ts declare global { namespace Cypress { interface Chainable { login(email: string, password: string, options?: { rememberMe?: boolean }): Chainable dataCy(value: string): Chainable> apiLogin(email: string, password: string): Chainable } } }

Cypress.Commands.add('login', (email: string, password: string, options = {}) => { // Implementation }) ```의 경우

제품 설명

Cypress 구성

카지노사이트

환경 변수

카지노사이트

다수 환경

카지노사이트

브라우저 설정

카지노사이트

페이지 개체

기본 페이지 개체

카지노사이트

Page Objects 사용

카지노사이트

고급 페이지 개체

```javascript // cypress/support/pages/DashboardPage.js class DashboardPage { constructor() { this.selectors = { userMenu: '[data-cy="user-menu"]', userProfile: '[data-cy="user-profile"]', notifications: '[data-cy="notifications"]', searchInput: '[data-cy="search"]', sidebar: '[data-cy="sidebar"]', mainContent: '[data-cy="main-content"]' } }

visit() { cy.visit('/dashboard') this.waitForLoad() return this }

waitForLoad() { cy.get(this.selectors.mainContent).should('be.visible') cy.get('.loading-spinner').should('not.exist') return this }

openUserMenu() { cy.get(this.selectors.userMenu).click() return this }

search(query) { cy.get(this.selectors.searchInput) .clear() .type(${query}{enter}) return this }

// Navigation methods navigateToProfile() { this.openUserMenu() cy.get(this.selectors.userProfile).click() return this }

// Assertion methods shouldShowWelcomeMessage(username) { cy.contains(Welcome, ${username}).should('be.visible') return this }

shouldHaveNotificationCount(count) { cy.get(this.selectors.notifications) .find('.badge') .should('contain', count) return this } }

export default DashboardPage ```의 경우

API 통합을 가진 Page Object

```javascript // cypress/support/pages/UsersPage.js class UsersPage { visit() { cy.intercept('GET', '/api/users').as('getUsers') cy.visit('/users') cy.wait('@getUsers') return this }

createUser(userData) { cy.intercept('POST', '/api/users').as('createUser')

cy.get('[data-cy="create-user-btn"]').click()
cy.get('[data-cy="name"]').type(userData.name)
cy.get('[data-cy="email"]').type(userData.email)
cy.get('[data-cy="save"]').click()

cy.wait('@createUser')
return this

}

deleteUser(userId) { cy.intercept('DELETE', /api/users/${userId}).as('deleteUser')

cy.get(`[data-cy="user-${userId}"]`)
  .find('[data-cy="delete-btn"]')
  .click()

cy.get('[data-cy="confirm-delete"]').click()
cy.wait('@deleteUser')
return this

}

shouldShowUser(userData) { cy.get('[data-cy="users-table"]') .should('contain', userData.name) .and('contain', userData.email) return this } }

export default UsersPage ```의 경우

API 테스트

기본 API 테스트

카지노사이트

API 인증

```javascript describe('Authenticated API Tests', () => { let authToken

before(() => { // Login and get token cy.request({ method: 'POST', url: '/api/auth/login', body: { email: 'admin@example.com', password: 'password123' } }).then((response) => { authToken = response.body.token }) })

it('should get protected resource', () => { cy.request({ method: 'GET', url: '/api/admin/users', headers: { 'Authorization': Bearer ${authToken} } }).then((response) => { expect(response.status).to.eq(200) expect(response.body).to.have.property('users') }) })

it('should fail without token', () => { cy.request({ method: 'GET', url: '/api/admin/users', failOnStatusCode: false }).then((response) => { expect(response.status).to.eq(401) }) }) }) ```의 경우

API 테스트 도우미

```javascript // cypress/support/api-helpers.js Cypress.Commands.add('apiLogin', (email, password) => { return cy.request({ method: 'POST', url: '/api/auth/login', body: { email, password } }).then((response) => { window.localStorage.setItem('authToken', response.body.token) return response.body.token }) })

Cypress.Commands.add('apiRequest', (method, url, body = null) => { const token = window.localStorage.getItem('authToken')

return cy.request({ method, url, body, headers: token ? { 'Authorization': Bearer ${token} } : {} }) })

// Usage cy.apiLogin('admin@example.com', 'password123') cy.apiRequest('GET', '/api/users') cy.apiRequest('POST', '/api/users', { name: 'John', email: 'john@example.com' }) ```를 호출합니다.

Schema 검증

```javascript // Install ajv for JSON schema validation // npm install --save-dev ajv

// cypress/support/schema-validation.js import Ajv from 'ajv'

const ajv = new Ajv()

Cypress.Commands.add('validateSchema', (data, schema) => { const validate = ajv.compile(schema) const valid = validate(data)

if (!valid) { throw new Error(Schema validation failed: ${JSON.stringify(validate.errors)}) } })

// Usage const userSchema = { type: 'object', properties: { id: { type: 'number' }, name: { type: 'string' }, email: { type: 'string', format: 'email' } }, required: ['id', 'name', 'email'] }

cy.request('GET', '/api/users/1') .then((response) => { cy.validateSchema(response.body, userSchema) }) ```의 경우

연락처

스크린 샷

```javascript describe('Visual Tests', () => { it('should match homepage screenshot', () => { cy.visit('/') cy.screenshot('homepage') })

it('should match element screenshot', () => { cy.visit('/dashboard') cy.get('[data-cy="user-profile"]').screenshot('user-profile') })

it('should match full page screenshot', () => { cy.visit('/products') cy.screenshot('products-page', { capture: 'fullPage' }) }) }) ```로

Percy와 비주얼 회귀

카지노사이트

오프화이트

사용자 정의 Visual Commands

카지노사이트

책임 시험

__CODE_BLOCK_49_로그

CI/CD 통합

GitHub 작업

카지노사이트

Docker 통합

```dockerfile

Dockerfile.cypress

FROM cypress/included:12.17.0

WORKDIR /app

COPY package*.json ./ RUN npm ci

COPY . .

Run tests

CMD ["npx", "cypress", "run"] ```를 호출합니다.

```yaml

docker-compose.yml

version: '3.8' services: app: build: . ports: - "3000:3000" environment: - NODE_ENV=test

cypress: build: context: . dockerfile: Dockerfile.cypress depends_on: - app environment: - CYPRESS_baseUrl=http://app:3000 volumes: - ./cypress/videos:/app/cypress/videos - ./cypress/screenshots:/app/cypress/screenshots ```의 경우

공급 능력

카지노사이트

시험 보고

카지노사이트

javascript // cypress.config.js module.exports = defineConfig({ e2e: { reporter: 'mochawesome', reporterOptions: { reportDir: 'cypress/reports', overwrite: false, html: false, json: true } } })

카지노사이트

최고의 연습

시험기관

카지노사이트

Selector 모범 사례

카지노사이트

최고의 연습

```javascript // ❌ Bad: Arbitrary waits cy.wait(3000) cy.get('button').click()

// ✅ Good: Wait for specific conditions cy.get('[data-cy="loading"]').should('not.exist') cy.get('[data-cy="submit-button"]').should('be.enabled').click()

// ✅ Good: Wait for network requests cy.intercept('POST', '/api/users').as('createUser') cy.get('[data-cy="submit"]').click() cy.wait('@createUser') ```에

Test Data 관리

```javascript // ✅ Good: Use fixtures for test data cy.fixture('users.json').then((users) => { const testUser = users.validUser cy.login(testUser.email, testUser.password) })

// ✅ Good: Generate dynamic test data const generateUser = () => ({ name: Test User ${Date.now()}, email: test${Date.now()}@example.com, password: 'password123' })

// ✅ Good: Clean up test data afterEach(() => { cy.task('cleanupTestData') }) ```의 경우

오류 처리

카지노사이트

관련 링크

Debug 명령

카지노사이트

다운로드

```javascript // Open DevTools programmatically cy.window().then((win) => { win.debugger })

// Inspect element in DevTools cy.get('[data-cy="element"]').then((\(el) => { debugger // Will pause in DevTools console.log(\)el[0]) // Inspect element })

// Access application state cy.window().its('store').then((store) => { console.log('Redux state:', store.getState()) }) ```의 경우

사용자 정의 디버그 명령

카지노사이트

시험 Debugging 전략

카지노사이트

- 연혁

시험 성과

카지노사이트

병렬 실행

카지노사이트

메모리 최적화

카지노사이트

문제 해결

일반적인 문제

카지노사이트

Debug 구성

```javascript // cypress.config.js module.exports = defineConfig({ e2e: { // Enable debug mode setupNodeEvents(on, config) { // Log all events on('task', { log(message) { console.log(message) return null } })

  // Debug failed tests
  on('after:spec', (spec, results) => {
    if (results && results.stats.failures) {
      console.log('Failed spec:', spec.relative)
      console.log('Failures:', results.stats.failures)
    }
  })
}

} })

// Usage in tests cy.task('log', 'Debug message here') ```의 경우

오류 복구

카지노사이트


제품정보

Cypress는 강력한 end-to-end 테스트 프레임 워크입니다.

  • Developer Experience: 실시간 브라우저 미리보기를 가진 직관적인 API
  • ** 자동 대기 ** : 요소 및 네트워크 요청에 대한 스마트 대기
  • 시간 여행: 각 단계에서 스냅 샷을 가진 디버그 테스트
  • Network Control: 네트워크 요청을 차단하고 수정
  • Real Browser Testing: 정확한 결과를 위한 실제 브라우저에서 실행되는 테스트
  • Rich Ecosystem: 광범위한 플러그인 생태계 및 통합
  • CI/CD 준비: 지속적인 통합을 위한 내장 지원
  • Visual Testing: 스크린 샷 및 시각적 회귀 테스트 기능

Cypress는 개발자 경험, 종합 디버깅 도구 및 신뢰할 수있는 테스트 실행에 중점을 둔 현대 웹 응용 프로그램을 테스트합니다. 독특한 건축과 특징은 강력한 end-to-end 테스트 워크플로우를 구현하는 팀을위한 훌륭한 선택입니다.

<문서> 기능 copyToClipboard () 이름 * const 명령어 = document.querySelectorAll('code'); let allCommands = ''; 명령. forEach(cmd =>의 경우 모든Commands +=cmd.textContent + navigator.clipboard.write텍스(allCommands); alert('모든 명령은 클립보드에 복사!'); 이름 *

함수 생성PDF() { 창. 인쇄 (); 이름 *