終於來到鐵人賽第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 URLcy.intercept('/users?_limit=*')
// match any request that satisfies a glob patterncy.intercept(/\\/users\\?_limit=(3|5)$/)
// match any request that satisfies a regex pattern
- 語法
// 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 的價值,有機會你也可以試試看自動化測試。
- 因官網的文件豐富,學習曲線較低
- 可以累積過往的測試案例
- 可以記錄測試結果,並將測試的過程錄製下來,輸出成可以量化的報告
- 可以整合 CI/CD 自動化測試
- 幫助測試人員找到系統的 bug