Using Cypress to E2E Testing
Preface
既然要完成一個 CI/CD flow, 一定要包含個自動化測試, 既然是 E2E Testing, 就來玩一下目前最夯的 Cypress
Setup
跑完之後 會在 Project 裡面多出一個路徑, 名稱是 cypress, 還有一個 cypress.json
cd cypress/integration
mkdir sample
touch index.spec.js
touch index_hash.spec.js
我們的目的是寫一個範例, 在 local 起一個 server, index page 在 http://localhost:3000, 讓 cypress 測試通過; 在 http://localhost:3000/#withHash 模擬其他頁面, 讓 cypress 測試失敗
// index.spec.js
describe('The Home Page', () => {
it('successfully loads', () => {
cy.visit('/')
})
})
// index_hash.spec.js
describe('The Home Page (with Hash)', () => {
it('successfully loads', () => {
cy.visit('/#withHash')
})
})
在 cypress.json 加入 local server url
# cypress.json
{
"baseUrl": "http://localhost:3000"
}
最重要的部分, 在 support/index.js 加入這段, 讓 cypress 可以捕捉 console 的 error 或 warning
// support/index.js
Cypress.on('window:before:load', (win) => {
cy.spy(win.console, 'error')
cy.spy(win.console, 'warn')
})
afterEach(() => {
cy.window().then((win) => {
expect(win.console.error).to.have.callCount(0)
expect(win.console.warn).to.have.callCount(0)
})
})
因為這邊 frontend 是用 vite, 在 src/App.vue, 模擬在其他頁面噴錯的狀況
// src/App.vue
if (!!window.location.hash) {
console.error('do some error')
}
Run Test
npx cypress run --spec 'cypress/integration/sample/*'
結果如下

Conclusion
用了一下 cypress 後發現其實語法和行為都蠻像之前用過的 puppeteer, 也有 headless 模式 (畢竟是一樣用 chromium 核心), 不過 cypress 有一個整合性非常好的 cloud service, 可以在上面的 Dashboard 看到整個完整的 testing record, 還可以串接 Github, Bitbucket, GitLab, Slack ...等等, 實在是方便又好用!
References
Using Cypress to E2E Testing
Preface
既然要完成一個 CI/CD flow, 一定要包含個自動化測試, 既然是 E2E Testing, 就來玩一下目前最夯的
CypressSetup
跑完之後 會在 Project 裡面多出一個路徑, 名稱是 cypress, 還有一個 cypress.json
cd cypress/integration mkdir sample touch index.spec.js touch index_hash.spec.js我們的目的是寫一個範例, 在 local 起一個 server, index page 在
http://localhost:3000, 讓 cypress 測試通過; 在http://localhost:3000/#withHash模擬其他頁面, 讓 cypress 測試失敗在 cypress.json 加入 local server url
最重要的部分, 在
support/index.js加入這段, 讓 cypress 可以捕捉 console 的 error 或 warning因為這邊 frontend 是用
vite, 在src/App.vue, 模擬在其他頁面噴錯的狀況Run Test
npx cypress run --spec 'cypress/integration/sample/*'結果如下
Conclusion
用了一下 cypress 後發現其實語法和行為都蠻像之前用過的
puppeteer, 也有 headless 模式 (畢竟是一樣用chromium核心), 不過 cypress 有一個整合性非常好的 cloud service, 可以在上面的 Dashboard 看到整個完整的 testing record, 還可以串接Github,Bitbucket,GitLab,Slack...等等, 實在是方便又好用!References
E2E Testing 初探
Cypress Docs
Cypress Dashboard