自動化測試,讓你上班擁有一杯咖啡的時間 | Day 30 — 學習cypress intercept 與後記

史卯郁
4 min readOct 14, 2021

--

此系列文章會同步發文到13th鐵人賽,有興趣的讀者可以前往觀看喔。

終於來到鐵人賽第30天!謝謝觀看我的文章和留言的所有人,第一次參加鐵人賽,每天早上都要提醒自己發文,比賽過程中遇到兩個連假,深怕自己會撐不到30天,感謝自己無數個深夜和清晨的努力,才能夠順利的完成比賽。

今天要跟大家分享 cy.intercept(),在 Cypress 6.0.0 後就不再使用 cy.server()cy.route()

使用 cy.intercept() 在網路層管理 HTTP 請求的行為。

  • 對 network requests 和 responses 進行 stub 或 spy
  • 在將 HTTP request 送到 server 之前可以修改 body, herders, URL 等等

method

可以用 GET, POST, PUT, PATCH, DELETE 等等

cy.intercept('/users')
// matches this: GET <http://localhost/users>
// ...and this, too: POST <http://localhost/users>
cy.intercept('GET', '/users')
// matches this: GET <http://localhost/users>
// ...but not this: POST <http://localhost/users>

url

可以用完整的 URL 或正規表示法

cy.intercept('<https://prod.cypress.io/users>')
// match any request that exactly matches the URL
cy.intercept('/users?_limit=*')
// match any request that satisfies a glob pattern
cy.intercept(/\\/users\\?_limit=(3|5)$/)
// match any request that satisfies a regex pattern
  1. 語法
// spying only
cy.intercept(url)
cy.intercept(method, url)
cy.intercept(routeMatcher)

2. 動手寫程式

describe('測試intercept', function() {
it('url用法', function(){
cy.intercept('<https://www.thsrc.com.tw/Event/LanguageSettings.json>')
})
it('method用法', function() {
cy.intercept('GET', '<https://www.thsrc.com.tw/Event/LanguageSettings.json>', { statusCode: 200,
})
})
})

最後跟大家分享導入 Cypress 的價值,有機會你也可以試試看自動化測試。

  1. 因官網的文件豐富,學習曲線較低
  2. 可以累積過往的測試案例
  3. 可以記錄測試結果,並將測試的過程錄製下來,輸出成可以量化的報告
  4. 可以整合 CI/CD 自動化測試
  5. 幫助測試人員找到系統的 bug

參考資料

--

--

No responses yet