I want to execute the multiple times same API with different payloads, but it's not working.
it('call same api with different payload',()=>{
cy.intercept('PATCH', `**/user/1`,{name:'thava'} ).as("action1")
cy.intercept('PATCH', `**/user/1`,{name:'prakash'} ).as("action2")
cy.visit('../app/intercept-identical.html');
cy.get("#update-action1").click();
cy.wait(['@action1']);
cy.get("#update-action2").click();
cy.wait(['@action2']); // not working
})
When requests are identical, only one intercept routeMatcher will catch all the calls.
To vary the response, one way is to respond with a function
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
})
Tested with
<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>
Note
req.reply(res => { res.send(...) } will not stub the request, it will only modify the response from the live server. If the server targeted is not able to accept 'PATCH', you will get an error.
If you update to the latest version of Cypress, you can simply over-write the intercept.
The last-added intercept will be the one to catch the request.
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
})