Cypress - cy.intercept catching wrong url

Viewed 2618

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 cypress@6.2.1)

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

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);
})
Related