Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress - cy.intercept catching wrong url

i try to mock my API routes with intercept but i don't know why it's the wrong route which triggered (i'm on [email protected])

i have two intercepts :

one for /contacts and second /contacts/Contact-ARandomId

cy.intercept('GET', 'http://localhost:5000/contacts', {statusCode: 200, body: dataMultiple})

cy.intercept('GET', 'http://localhost:5000/contacts/Contact-ARandomId', {statusCode: 200, body: dataARandomId})

image image

like image 400
JustinMartinDev Avatar asked Aug 31 '25 17:08

JustinMartinDev


1 Answers

Ref Matching URL

You can provide a substring of the URL to match

// will match any request that contains "users" substring, like
// GET /users?_limit=3 and POST /users

cy.intercept('users')

so 'http://localhost:5000/contacts' matches because it is the first defined, and partial matching applies.

You could just reverse the order of the intercepts, set the more specific URL first (sort of like routes on a SPA).

Alternatively, take a look at Set an alias dynamically.

You can use javascript to refine the response

cy.intercept('GET', 'http://localhost:5000/contacts', (req) => {

  const isContactById = req.url.split('/')  // split into parts
    .pop()                                  // take last part
    .startsWith('Contact-');                // check if has id prefix

  const bodyStub = isContactById ? dataARandomId : dataMultiple;
  req.reply(200, bodyStub);
})
like image 136
Richard Matsen Avatar answered Sep 02 '25 09:09

Richard Matsen