0

Hello so am relatively new to using intercept on cypress. Clicking a button sends a request. Intercepting and not stubbing (//1) lets me retrieve the date value in the response seen in cy.log($resp.response), but I need to stub a response too (//2) this fails to return a date value in the cy.log($resp.response). The data value is generated as it is seen in the UI How can I retrieve the response and still stub?

    cy.intercept({method: 'POST', url: '**/myURL'}).as('successfulAction')  //1      
    cy.intercept({method: 'POST', url: '**/myURL'},{stubbed data}).as('successfulAction') //2
    cy.get('button').click()
    cy.wait('@successfulAction').then(($resp) => {
        cy.log($resp.response)
    })
Fody
  • 23,754
  • 3
  • 20
  • 37

3 Answers3

0

On the first intercept, add the middleware flag.

This allows the true request to be caught, but pass the request on to the 2nd intercept which applies stubbed data.

cy.intercept({
  method: 'POST', 
  url: '**/myURL',
  middleware: true
}).as('successfulAction')     

cy.intercept({method: 'POST', url: '**/myURL'}, {stubbed data}) // no alias needed

cy.wait('@successfulAction')
  .then(($resp) => {
    cy.log($resp.response)
  })
Fody
  • 23,754
  • 3
  • 20
  • 37
0

You can also use a single intercept

cy.intercept({
  method: 'POST', 
  url: '**/myURL',
  middleware: true
}).(req => {
  req.continue(resp => {
    cy.log($resp.response)
    res = stubbedData
  })
})

.as('successfulAction')

TesterDick
  • 3,830
  • 5
  • 18
0

Thanks for the answers I definitely gave me an idea and the below works.

    cy.intercept({
        method: 'POST', 
        url: `**/${parentAlarmsAssetsData[0].AssetNumber}`,
        middleware: true
    },(req) => {
        req.continue((res) => {
            res.send({ //add stubbed data
                statusCode: 200,
                body: {
                    "status":true,
                    "responseMessage":null
                }
            })
        })
    }).as('successfulAction')
      
    cy.get(manualCheckButton).click()
    cy.wait('@successfulAction').then(($resp) => {
        acknowledgedDateTime = $resp.response.headers.date //set global var
    })