Search code examples
cypresscy.intercept

cy.intercept is not matching the desired url


I am trying to use cy.intercept to match a url, however it seems to be intercepting a different url. I want to intercept the API request made when I click a save button, when this button is clicked, it makes a request to these two endpoints (for example)

POST https://api.example.com/test/foo/bar

POST https://api.example.com/test/foo

I want to intercept the second call only, however, it seems like everytime, it would always intercept the first one and not the second one. In my code, I am just doing the following:

cy.intercept('POST', 'https://api.example.com/test/foo').as('foo');

I have tried intercepting both the requests, but somehow it always picks catches the foo/bar endpoint instead. Am I doing something wrong? I had assumed it would do an exact match of what I passed in the cy.intercept request. Could it be because the request I am trying to intercept has the form-data type? Or simply because its the first request? (sounds a bit weird to me)

Any help would be greatly appreciated!

Thank you in advance!

EDIT: For work purposes, unfortunately I am not able to share the exact code, however, its roughly like this

 before(() => {
    cy.intercept('POST', 'https://api.example/com/test/foo').as('foo');
    });

Given('Test bla3x 1', async () => {
    cy.get(element).click();
});

Then('test bla3x 2', async () => {
    cy.wait('@foo').then((response) => {
        console.log(response);
    })
})

To run the tests, at the moment I am just using the normal cypress runner, and as I mentioned earlier, the result of the console.log is incorrect because its intercepting the /foo/bar url instead of /foo. I also forgot to mention that I am using cucumber preprocessor with cypress.... although I don't believe that's related to this issue, since I did manage to intercept some other urls.


Solution

  • You can use regex to match the url you want. $ is used to match the ending of the string so you'll only spy on the POST https://api.example.com/test/foo call.

    cy.intercept('POST', /https:\/\/api.example.com\/test\/foo$/).as('foo');