当请求相同时,只有一个拦截器routeMatcher
会捕获所有调用。
要改变响应,一种方法是使用函数响应
it('responds to identical requests with different responses', () => {
let requestNo = 0
const responses = [ { name: 'thava' }, { name:'prakash' } ]
cy.intercept('PATCH', '**/user/1', (req) => {
req.reply(responses[requestNo++])
}).as('action');
cy.visit('../app/intercept-identical.html')
cy.get("#update-action").click()
cy.wait('@action')
.its('response.body.name')
.should('eq', 'thava') // passes
cy.get("#update-action").click()
cy.wait('@action')
.its('response.body.name')
.should('eq', 'prakash') // passes
})
经测试
<body>
<button id="update-action" onclick="clickhandler()"></button>
<script>
function clickhandler() {
fetch('https://jsonplaceholder.typicode.com/user/1', {
method: 'PATCH'
})
.then(res => res.json())
}
</script>
</body>
笔记
req.reply(res => { res.send(...) }
不会存根请求,它只会修改来自实时服务器的响应。如果目标服务器无法接受“PATCH”,您将收到错误消息。
覆盖拦截
如果您更新到最新版本的赛普拉斯,您可以简单地覆盖拦截。
最后添加的拦截将是捕获请求的拦截。
it('overrides intercepts', () => {
cy.visit('../app/intercept-identical.html')
cy.intercept('PATCH', `**/user/1`, { name:'thava' } ).as("action1")
cy.get("#update-action").click()
cy.wait('@action1')
.its('response.body.name')
.should('eq', 'thava') // passes
cy.intercept('PATCH', `**/user/1`, { name:'prakash' } ).as("action2")
cy.get("#update-action").click()
cy.wait('@action2')
.its('response.body.name')
.should('eq', 'prakash') // passes
})