Home > Net >  Cypress - intercept two endpoints in same spec file
Cypress - intercept two endpoints in same spec file

Time:10-07

I am having trouble intercepting 2 api's in the same spec file. The endpoints are

  1. client/users
  2. client/users/ipuser

Issue: It captures the users response in ipuser json. Can someone please help on how to use regex in the endpoints.

cy.intercept('GET', '/client/users/ip_user', { fixture: 'ipuser.json' }).as('ipuser')
       cy.intercept('GET', '/client/users', { fixture: 'users.json' }).as(
        'user'
    )
 cy.wait('@ipuser').then((interception) => {
            interception.response.body.data.attributes.limit = 10000
            interception.response.body.data.attributes.amount = 10000
             cy.log(JSON.stringify(interception.response.body))
            cy.writeFile(filename, JSON.stringify(interception.response.body))
          })

        cy.intercept('GET', '/client/users/ip_user', {
            fixture: 'ipuser.json',
        }).as('ipuser')        

CodePudding user response:

You will use regex match your urls by the ending and will need to escape the slashes.

cy.intercept('GET', /\/client\/users\/ipuser$/, { fixture: 'ipuser.json' }).as('ipuser')
cy.intercept('GET', /\/client\/users$/, { fixture: 'users.json' }).as('user')

CodePudding user response:

There seems to be a couple of problems,

  • you have two intercepts for @ipuser

  • if you are dynamically writing ipuser.json, you will need to dynamically assign it in the intercept.

Presume it's the cy.visit('/') that triggers the requests, this is how it should look

// set up both intercepts at the top of the test
// the more specific URL (/client/users/ip_user) should go last

cy.intercept('GET', '/client/users', {fixture: 'users.json'}).as('user')

cy.intercept('GET', '/client/users/ip_user', req => {
  req.reply({fixture: 'ipuser.json'})                  // responds after the fixture is written
}).as('ipuser')  

// trigger the fetches
cy.visit('/')

// wait on the 1st - presume it creates the fixture for the second
const filename = './cypress/fixtures/ipuser.json'
cy.wait('@user').then((interception) => {
  interception.response.body.data.attributes.limit = 10_000
  interception.response.body.data.attributes.amount = 10_000
  cy.writeFile(filename, interception.response.body)  // JSON.stringify not needed
})

// wait on the 2nd and check it's result
cy.wait('@ipuser')
  .its('response.body')
  .should('have.property', 'data')
  .should('have.property', 'attributes')
  .should('have.property', 'limit', 10_000)
  • Related