3

Consider a page which allows you to select a vehicle like car, truck and bike. You can save the selection by pressing a Save button. The save button will trigger the appropriate api call depending on the type of vehicle you selected i.e. POST /Inventory/AddCar, /Inventory/AddTruck, /Inventory/AddBike. In cypress, I want to intercept all these calls when the save button is clicked and then wait for the calls to complete. I tried using regex in my intercept as follows, but it did not work. How do I intercept multiple api calls which essentially do the same thing?

// A (web) page object function.
function saveVehicle()
{
  const regex = `/[\/Inventory\/AddCar]|[\/Inventory\/AddTruck]|[\/Inventory\/AddBike]/`
  cy.intercept("POST", regex).as("saveVehicle");
  saveButton.click().wait("@saveVehicle");
}
MasterJoe
  • 2,103
  • 5
  • 32
  • 58

2 Answers2

3

A regex is supposed to work, but you might find it easier to use javascript inside a routeHandler.

cy.intercept("POST", '/Inventory/*', (req) => {
  if (req.url.includes('AddCar') || req.url.includes('AddTruck') || req.url.includes('AddBike')) {
    req.alias = 'saveVehicle'
  }
})

saveButton.click()
cy.wait("@saveVehicle")

Also from docs,

It is unsafe to chain further commands that rely on the subject after .click()

Unsure if that applies here, but better to follow safer practice.

  • Thanks. This works, but the cypress runner says that request is modified but there is no alias. Why does that happen? I was expecting the alias to show up. – MasterJoe May 23 '23 at 22:45
3

The square brackets denote a single character out out those inside, rather than the complete string.

You can use round brackets instead (matching group), or no brackets at all.

Also, do not use string delimiters if applying the regex directly, / delimiters are sufficient.

const regex = /(\/Inventory\/AddCar)|(\/Inventory\/AddTruck)|(\/Inventory\/AddBike)/
cy.intercept('POST', regex).as('saveVehicle')

Practice your regex here.

Lola Ichingbola
  • 3,035
  • 3
  • 16
  • This works well. Unlike the 2nd answer, I don't get "there is no alias" message in the cypress runner which is good. – MasterJoe May 23 '23 at 22:51