Cypress 완벽 가이드 | E2E 테스트·자동화·CI/CD·실전 활용
이 글의 핵심
Cypress로 E2E 테스트를 구현하는 완벽 가이드입니다. Commands, Assertions, Fixtures, Intercept, CI/CD 통합까지 실전 예제로 정리했습니다.
실무 경험 공유: Selenium에서 Cypress로 전환하면서, 테스트 작성 시간이 60% 단축되고 안정성이 크게 향상된 경험을 공유합니다.
들어가며: “E2E 테스트가 어려워요”
실무 문제 시나리오
시나리오 1: Selenium이 불안정해요
Flaky 테스트가 많습니다. Cypress는 자동 대기로 안정적입니다.
시나리오 2: 디버깅이 어려워요
에러 추적이 복잡합니다. Cypress는 Time Travel로 쉽게 디버깅합니다.
시나리오 3: 설정이 복잡해요
WebDriver 설정이 번거롭습니다. Cypress는 즉시 사용 가능합니다.
1. Cypress란?
핵심 특징
Cypress는 모던 E2E 테스트 프레임워크입니다.
주요 장점:
- 자동 대기: Flaky 테스트 방지
- Time Travel: 디버깅 쉬움
- 실시간 리로드: 빠른 피드백
- 스크린샷/비디오: 자동 캡처
- API Mocking: 네트워크 제어
2. 설치 및 설정
설치
npm install -D cypress
실행
npx cypress open
cypress.config.ts
import { defineConfig } from 'cypress';
export default defineConfig({
e2e: {
baseUrl: 'http://localhost:3000',
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
viewportWidth: 1280,
viewportHeight: 720,
video: true,
screenshotOnRunFailure: true,
});
3. 기본 테스트
// cypress/e2e/login.cy.ts
describe('Login', () => {
beforeEach(() => {
cy.visit('/login');
});
it('로그인 성공', () => {
cy.get('input[name="email"]').type('[email protected]');
cy.get('input[name="password"]').type('password123');
cy.get('button[type="submit"]').click();
cy.url().should('include', '/dashboard');
cy.contains('Dashboard').should('be.visible');
});
it('로그인 실패 - 잘못된 비밀번호', () => {
cy.get('input[name="email"]').type('[email protected]');
cy.get('input[name="password"]').type('wrong');
cy.get('button[type="submit"]').click();
cy.contains('Invalid credentials').should('be.visible');
});
});
4. Commands
기본 Commands
// 방문
cy.visit('/');
// 선택
cy.get('.btn');
cy.contains('Submit');
cy.get('[data-testid="user-list"]');
// 액션
cy.get('input').type('Hello');
cy.get('button').click();
cy.get('select').select('Option 1');
cy.get('input[type="checkbox"]').check();
// Assertions
cy.get('.title').should('have.text', 'Hello');
cy.get('.btn').should('be.visible');
cy.get('.btn').should('be.disabled');
cy.url().should('include', '/dashboard');
5. Intercept (API Mocking)
describe('Users', () => {
beforeEach(() => {
cy.intercept('GET', '/api/users', {
statusCode: 200,
body: [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
],
}).as('getUsers');
cy.visit('/users');
});
it('사용자 목록 표시', () => {
cy.wait('@getUsers');
cy.contains('John').should('be.visible');
cy.contains('Jane').should('be.visible');
});
});
6. Fixtures
Fixture 파일
// cypress/fixtures/users.json
[
{ "id": 1, "name": "John", "email": "[email protected]" },
{ "id": 2, "name": "Jane", "email": "[email protected]" }
]
사용
describe('Users', () => {
beforeEach(() => {
cy.fixture('users').then((users) => {
cy.intercept('GET', '/api/users', users).as('getUsers');
});
cy.visit('/users');
});
it('사용자 목록 표시', () => {
cy.wait('@getUsers');
cy.contains('John').should('be.visible');
});
});
7. Custom Commands
// cypress/support/commands.ts
declare global {
namespace Cypress {
interface Chainable {
login(email: string, password: string): Chainable<void>;
}
}
}
Cypress.Commands.add('login', (email, password) => {
cy.visit('/login');
cy.get('input[name="email"]').type(email);
cy.get('input[name="password"]').type(password);
cy.get('button[type="submit"]').click();
});
// 사용
cy.login('[email protected]', 'password123');
8. CI/CD 통합
GitHub Actions
# .github/workflows/cypress.yml
name: Cypress Tests
on: [push]
jobs:
cypress-run:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Cypress run
uses: cypress-io/github-action@v6
with:
build: npm run build
start: npm start
wait-on: 'http://localhost:3000'
9. Component Testing
// src/components/Button.cy.tsx
import Button from './Button';
describe('Button', () => {
it('renders', () => {
cy.mount(<Button label="Click me" />);
cy.contains('Click me').should('be.visible');
});
it('handles click', () => {
const onClickSpy = cy.spy().as('onClickSpy');
cy.mount(<Button label="Click me" onClick={onClickSpy} />);
cy.contains('Click me').click();
cy.get('@onClickSpy').should('have.been.calledOnce');
});
});
정리 및 체크리스트
핵심 요약
- Cypress: E2E 테스트 프레임워크
- 자동 대기: Flaky 테스트 방지
- Time Travel: 디버깅 쉬움
- Intercept: API Mocking
- Fixtures: 테스트 데이터
- CI/CD: GitHub Actions 통합
구현 체크리스트
- Cypress 설치
- 기본 테스트 작성
- Commands 활용
- Intercept 사용
- Fixtures 활용
- Custom Commands 작성
- CI/CD 통합
- Component Testing
같이 보면 좋은 글
- Playwright 완벽 가이드
- Vitest 완벽 가이드
- GitHub Actions 완벽 가이드
이 글에서 다루는 키워드
Cypress, E2E, Testing, Automation, CI/CD, Frontend, TypeScript
자주 묻는 질문 (FAQ)
Q. Playwright와 비교하면 어떤가요?
A. Cypress가 더 쉽고 DX가 좋습니다. Playwright는 더 빠르고 다양한 브라우저를 지원합니다.
Q. 실제 브라우저를 사용하나요?
A. 네, Chrome, Edge, Firefox를 지원합니다.
Q. 모바일 테스트도 가능한가요?
A. Viewport를 조정해 모바일 시뮬레이션이 가능합니다.
Q. 프로덕션에서 사용해도 되나요?
A. 네, 수많은 기업에서 안정적으로 사용하고 있습니다.