若要在 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 官方所提供 imageports:
:設定對外為 port8080
,對內為 port80
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 官方所提供 imageenvironment
:設定baseUrl
環境變數,直接指向vue
containervolumes
:將專案的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
:先編譯 Vuedocker compose up
:再執行docker compose
$ yarn test:docker
執行 docker-compose
將啟動 Cypress 測試。
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