How to wait for a request from a different URL in Cypress test?

Viewed 84

In my Cypress test, I am trying to wait for a GET request & validate it's response. However, the test is timing out as the request never occurs.

Here is the request I am trying to wait for:

enter image description here

Here are some details around the test:

  • The URL of the app I am visiting in the test is https://ts-e2e-challenge.netlify.app/list.
  • In my test, an action is performed that sends a GET request to the URL https://bookshelf.jk/api/list-items, as you can see in the screenshot.

And here is my test code:

cy.intercept('GET', '/list-items').as('getListItems')
cy.wait('@getListItems').then((interception) => {
});

Full error message:

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

I assume the URL that I am trying to intercept is incorrect, but I have tried to update it to the full path https://bookshelf.jk/api/list-items, but the request is still not being made.

Can someone please point out what the request URL should be based on the above screenshot?

2 Answers

I think the issue here is your request is not intercepted properly, You can try this:

cy.intercept('GET', '**/api/list-items').as('getListItems')
cy.wait('@getListItems').then((interception) => {
  //Do something
})

There's a service worker intercepting the network requests before Cypress can intercept them.

If you put https://bookshelf.jk/api/list-items into a normal browser, it can't be reached. That's because the service worker is acting like the (non-existing) API server.

For the record, the full URL https://bookshelf.jk/api/list-items should work. Also /api/list-items would work if your baseUrl was common to the web page and the api (as you surmised).

As far as I can see, there's no simple adjustment to fix it. You may be able to hack the loading of the service worker but if you're just trying out cy.intercept() it's not worth the effort.

I'd look for another site to test against, https://jsonplaceholder.typicode.com is a good one.

Related