Search code examples
cypresscy.intercept

Cypress intercept and change the request


I am trying to intercept an a request. This request has a specific endpoint and I would like to change this endpoint.

I have now solved it with the following code:

cy.intercept('**/i18n/nl.json', { fixture: 'LanguageForItemEditorENG.json' }).as('Language')

As you can see I have used a fixture, but I don't think that this is the best practice. My testcode would be more robust if I can route the request to

'**/i18n/en.json'

and not use a fixture.

So, at this moment the application is making a request to **/nl.json but I want to simulate this so the application gets the response of the **/en.json. How can I make this work?


Solution

  • You can intercept the request and modify certain properties before continuing.

    cy.intercept('**/i18n/nl.json', (req) => {
      req.url = req.url.replace('/i18n/nl.json', '/i18n/en.json');
      req.continue();
    }).as('Language')
    

    Aside: I don't think that stubbing the response is necessarily a bad idea. If you just need some data, then stubbing that data is fine. The only time that I would see that I absolutely need a network response would be a true, complete end-to-end test (of which you should have very few in your suite), or if I were specifically testing that endpoint.