Search code examples
javascripttestingautomated-testscypress

cy.intercept() not working when used with cy.trigger()


I have an input with type=date in my form. When its value changes, the app is supposed to call the API /get_slots with POST method. I used cy.type() and then cy.trigger('change') to trigger the API call.

I wanted to use cy.intercept() to return mocked data from the fixture file. However, it seems like cy.intercept() is never invoked, and the actual API is still being called instead.

Here is the code:

// It is supposed to return the slots from fixture file
cy.intercept('POST', '/get_slots', 'fixture:slot-list.json').as('getSlots');

cy.get('input.datepicker')
  .type("2024-01-10")
  .trigger('change')

In the ROUTE section, Cypress shows stubbed = YES

enter image description here

I tried to use cy.wait("@getSlots") but it shows:

Timed out retrying after 5000ms: cy.wait() timed out waiting 5000ms for the 1st request to the route: getSlots. No request ever occurred.Learn more

Can anyone help me understand the error here and how to fix it?


Solution

  • In the screenshot the last column shows the number of hits/matches to the intercept. - means no hits.

    So either the URL sent from the app to the API does not match /get_slots or the POST never happened.

    Does POST occur

    Take a look in the devtools Network tab to see if you POST actually occurs. It may be that .trigger('change') is the wrong event, you may need .trigger('input') or cy.get('form').trigger('submit').

    If you have access to the source code, you can find out what event is being used.

    Sometimes you can only get an event to fire using the cypress-real-events plugin, try that as well.

    What routeMatcher is needed

    If the POST is present in devtools, the fault is with the routeMatcher expression, so you need to look at the full URL in devtools and compare it.

    The /get_slots expression is a glob expression which can be surprisingly finicky. Try wild-carding the previous and following paths **/get_slots/*.

    Note the get_slots should be a complete path segment, i.e all the text between two path separator in the actual URL.

    Some other ways routeMatcher can be used

    • full URL string (paste in the full URL from devtools)

    • regex /\/get_slots/