點燈坊

失くすものさえない今が強くなるチャンスよ

使用 Docker Compose 執行 Cypress

Sam Xiao's Avatar 2021-04-03

若要在 CI 以 Cypress 測試 Vue,勢必面對 Cypress Dependency 與 Web Server 執行 Vue 問題,我們可透過 docker compose 同時執行 Cypress 與 Nginx 兩個 Container 進行測試。

Version

Vue 3.0.11
Cypress 7.4.0

Docker Compose

docker-compose.yml

version: "3"
services:
  vue:
    image: nginx:alpine
    restart: always
    ports:
      - "8080:80"
    volumes:
      - ./dist:/usr/share/nginx/html
  cypress:
    image: cypress/included:7.4.0
    environment:
      - CYPRESS_baseUrl=http://vue
    volumes:
      - ./cypress:/cypress
      - ./cypress.json:/cypress.json
    command: npx cypress run

第 3 行

vue:
  image: nginx:alpine
  restart: always
  ports:
    - "8080:80"
  volumes:
    - ./dist:/usr/share/nginx/html

設定 Vue container:

  • image: nginx:alpine:使用 Nginx 官方所提供 image
  • ports::設定對外為 port 8080,對內為 port 80
  • volumns:將 dist 目錄對應用 container 內部的 /usr/share/nginx/html

10 行

cypress:
    image: cypress/included:7.4.0
    environment:
      - CYPRESS_baseUrl=http://vue
    volumes:
      - ./cypress:/cypress
      - ./cypress.json:/cypress.json
    command: npx cypress run

設定 Cypress container:

  • image: cypress/included:7.4.0:使用 Cypress 官方所提供 image

  • environment:設定 baseUrl 環境變數,直接指向 vue container

  • volumes:將專案的 cypress 目錄與 cypress.json 設定檔對應到 container 內部

  • command: npx cypress run:執行 Cypress

CYPRESS 為開頭的變數將成為 Node 環境下的全域變數

NPM Script

package.json

{
  "name": "vue3-cypress",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview",
    "test:gui": "cypress open",
    "test:cli": "cypress run --spec 'cypress/integration/*'",
    "test:docker": "yarn build && docker compose up"
  },
  "dependencies": {
    "vue": "^3.0.5"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^1.2.2",
    "@vue/compiler-sfc": "^3.0.5",
    "cypress": "^7.4.0",
    "vite": "^2.3.4"
  }
}

10 行

"test:docker": "yarn build && docker compose up"
  • yarn build:先編譯 Vue
  • docker compose up:再執行 docker compose
$ yarn test:docker

執行 docker-compose 將啟動 Cypress 測試。

docker000

Conclusion

  • 使用 docker compose 讓我們不用擔心 Cypress 與 Nginx dependency,只要一個 docker-compose.yml 文字檔就可執行測試

Reference

Michael Lynch, End-to-Ent Testing Web Apps: The Painless Way
Gleb Banmutov, Run Cypress with a single Docker command
Cypress, Docker