Search code examples
cypresscypress-intercept

Cypress intercept match not matching a single word


I have read the docs on Cypress v6.9.1 about intercept but I'm having some difficulties truly understanding how to match single words urls.

A practical example of a problem I'm facing. I'm making the following request to create a label in my app:

POST http://localhost:8081/70e70322-1633-4ca9-b1e2-9240cef416e7/label

I would assume, from the docs that I could match this route just by doing:

// My code
cy.intercept("POST", "/label").as("createLabel");

// From the examples in Cypress pages
cy.intercept('GET', '/users')
// matches this: GET http://localhost/users
// ...but not this: POST http://localhost/users

I have tried the following approaches:

// Passing a simple string
cy.intercept("POST", "label").as("createLabel");

// Passing a regex
cy.intercept("POST", /label/g).as("createLabel");

// Passing a glob pattern
cy.intercept("POST", "**/label").as("createLabel");

I'm scratching my head with this one and not truly understanding what exactly is the way to intercept a request based on a single word. This is a simple example but I have faced this problem in many other tests where, to solve my problem I had to intercept all requests (which makes my tests brittle and not future proof):

// This is just a "hacky" way to make it work and avoid the app to 
// make a request to my backend after creating another resource
cy.intercept("GET", "*");

Question

How can I make Cypress match a single word in a request?

  • GET http://localhost/label -> please, intercept the requests that has label on the URL
  • POST http://localhost/user/{userId}/comment -> please, intercept the requests that has user on them
  • POST http://localhost/user/{userId}/comment -> please, intercept the requests that has comment on them

Solution

  • With the help of @Sebastiano I used minimatch and discovered that when I don't add the options it doesn't match.

    An example:

    // doesnt match
    cy.intercept("POST", "**/label").as("createLabel");
    
    // it maches
    cy.intercept("POST", "**/label", { statusCode: 200 }).as("createLabel");