THE DEVLOG

scribbly.

자주쓰는 라이브러리

2025.06.25 00:57:51

Cypress는 브라우저를 직접 통제하는 E2E 테스트 도구이다.

특히 Next.js 등의 SSR을 테스트하기 위해서는 컴포넌트 테스트 만으로는 구성이 불가능하여 사용하게 된다.

Playwright가 보다 브라우저를 정밀하게 통제하는 이점이 있으나, 국내에는 아직 Cypress가 더 많이 쓰인다.

참조

유튜브- Code Ryan - Master Next.js Testing with Cypress: A Step-by-Step Guide
Code Ryan GitHub

공식문서 - How to set up Cypress with Next.js

설정하기

Cypress 설치

npm install -D cypress

package.json 설정

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "cypress:open": "cypress open"
  }
}

 

Cypress 실행하기

npm run cypress:open

Cypress 기본 config

cypress.config.ts 파일을 아래와 같이 작성한다

import { defineConfig } from "cypress";

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {},
  },
});

setupNodeEvents는 Node.js 런타임 환경에서의 이벤트를 설정한다.

on을 통해 이벤트를 설정할 수 있으며 before:browser:launch, task, file:preprocessor 등을 통해 브라우저를 실행할 때를 설정할 수 있다.

config는 cypress의 config를 담고 있는 객체이며, 수정도 가능하다.

import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000', // baseUrl 설정
    setupNodeEvents(on, config) {
      // 브라우저 실행 전 크기 조정
      on('before:browser:launch', (browser, launchOptions) => {
        if (browser.name === 'chrome') {
          launchOptions.args.push('--window-size=1400,900')
        }
        return launchOptions
      })
      // (config 수정 - defaultCommandTimeout 변경
      config.defaultCommandTimeout = 8000
      return config
    },
  },
})

 

컴포넌트 테스트 config

컴포넌트 테스트를 위해서는 작동하는 환경을 추가해주어야 한다.

import { defineConfig } from "cypress";

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {},
  },
  // next.js를 위한 컴포넌트 테스트 설정
  component: {
    devServer: {
      framework: "next",
      bundler: "webpack",
    },
  },
});

 

Cypress Runner

npm run cypress:open을 입력하면 Cypress Runner가 실행되고, 원하는 브라우저와 함께 테스팅을 수행하게 된다.

1.00