Cypress: cy.wait() always gives a timeout error: No request ever occurred.

Created on 11 Feb 2019  ·  125Comments  ·  Source: cypress-io/cypress

Current behavior:

I am just following he tutorial at your site and there is a part when cy.wait('@alias') is shown.

On the video it worked fine, However I always getting an error

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

I have tried it both in my project and in your completed tutorial project
The error is present in both cases.

Here is an image
Request is going

When I don't use cy.wait() it seems to work fine

Can you help me with this please?

Desired behavior:

cy.wait should for the request to resolve

Versions

"cypress": "3.1.5",
Google Chrome Version 71.0.3578.98

needs information cy.wait() timeout bug

Most helpful comment

meeting this error, too...
Is there any solution?

All 125 comments

@t-zander thanks for opening an issue with screenshots. In the DevTools, can you fetch the type of the request - is it XHR or fetch? Because currently Cypress can only spy / stub / wait on XHR requests See the warning in https://docs.cypress.io/api/commands/route.html#Syntax and a couple of workarounds in that case

It's weird but error happened with syntax like cy.route('POST', 'url')
While in syntax like

cy.({
method: ....
})

Its gone.

Can you provide the full test code please?

Hi, sorry, it seems like the problem came again. I will share the code. (Sorry if something is wrong with it, but I just followed your tutorial movies)
I have a setTimeout() to imitate a network delay in all below cases

This way it works okay

context('With no todos', () => {
    it.only('saves new todo', () => {
      cy.visit('/')
      cy.server()
      cy.route({
        url: 'api/todos',
        method: 'POST'
      })
      .as('create');


      cy.focused()
        .type('buy milk')
        .type('{enter}')

      cy.wait('@create')

      cy.get('.todo-list')
        .should('have.length', 1)
    })
  });`

This way I have failing test (sometimes its working hovewer). In failing case it gives a timeout error
and says

No request ever occurred.

However, in panel I can clearly see xhr requests

context('With no todos', () => {
    it.only('saves new todo', () => {
      cy.visit('/')
      cy.server()
      cy.route('POST', 'api/todos')
        .as('create');


      cy.focused()
        .type('buy milk')
        .type('{enter}')

      cy.wait('@create')

      cy.get('.todo-list')
        .should('have.length', 1)
    })
  });

Now if I have consequent requests like these it also gives me an error

context('With no todos', () => {
    it.only('saves new todo', () => {
      const items = [
        {text: 'Buy milk', expectedLength: 1},
        {text: 'Buy bread', expectedLength: 2},
        {text: 'Buy butter', expectedLength: 3}
      ]
      cy.visit('/')
      cy.server()
      cy.route('POST', 'api/todos')
        .as('create');

      cy.wrap(items)
        .each((item) => {
          cy.focused()
            .type(item.text)
            .type('{enter}')

          cy.wait('@create')

          cy.get('.todo-list')
            .should('have.length', item.expectedLength)
        })
    })
  });

Here is a lightshot screenshot
http://prntscr.com/mk86sk

@t-zander The error you posted looks unrelated to the original issue you opened correct? I don't see any failure during the cy.wait() in the example.

@jennifer-shehane
The second example sometimes gives tmeout error.
Third one is not directly connected but iit has to do with cy.wait()
May you please give me a hint why it may happen?(I mean third example)
thank you very much in advance

@jennifer-shehane my colleagues are seeing this as well. any updates here?

We'll need a reproducible example in order to look into this further.

meeting this error, too...
Is there any solution?

What can be the issue is the api/todos.
I had a similar issue where I waited for /oauth/v2/token/, apparently the call was to /oauth/v2/token.
The slashes before and after seem to matter.
Check if your call is to api/todos.

I guess not, as the path always starts with a slash right?

Unfortunately we'll have to close this issue if no reproducible example is provided. Can anyone provide a way to reproduce this?

I just ran into this error, and this comment was the clue. I wasn't specifying the request method POST. I was under the assumption it matched any method to the url. That was the core of my problem.

Without a method:
image

With the method:
image

I had the same issue but solved it by moving cy.server(); and cy.route(...); before cy.visit().

I had an issue where cy.get(...).type(...).wait('@alias') was giving a timeout only in headless mode. I decided the network response was just too fast and was completed before the wait was registered (admittedly, I have no idea how wait works). I removed the wait, no more timeouts. But then I had a weird situation where the network response was faster than cypress and cypress was faster than the renderer so I had to add checks that the content updated before continuing the object click-fest that is my test. Hope this makes sense.

edit: to clarify...

// BEFORE
cy.get('.my-autocomplete input[type="text"]').type('THE TEXT').wait('@algolia')
cy.get('.v-autocomplete__content.menuable__content__active .v-list__tile:first').click()
// AFTER
cy.get('.my-autocomplete input[type="text"]').type('THE TEXT')
cy.get('.v-autocomplete__content.menuable__content__active .v-list__tile:first').contains('THE TEXT').click()

Unfortunately we have to close this issue as there is not enough information to reproduce the problem.

Please comment in this issue with a reproducible example and we will reopen the issue. 🙏

I had a similar issue where XHR requests were never made. Solved this using this in my tests/cypress/support/index.js. Worked for me ever since.

// Hack to always bind cy.server() to bind to webAppWindow
Cypress.on('window:load', (window) => {
    // Get webApp iframe
    const docIframe = window.parent.document.getElementById("Your App: 'cypress'");
    const webAppWindow = docIframe.contentWindow;

    // Get current cypress server thats started
    const server = Cypress.state().server;
    if (server) {
        // bind server to our webApp window
        server.bindTo(webAppWindow);
    }
});

I am having the same issue as @t-zander
image of test failing:

describe.only("List Item Behavior", () => {
  it("Deletes and item", () => {
    cy.server()
    cy.route({
      method: "DELETE",
      url: "/todos/*",
      response: {}
    }).as("delete")
    cy.seeAndVisit()

    cy
    .get(".todo-list li")
    .as('list')

    cy.get('@list')
    .first()
      .find(".destroy")
      .invoke("show")
      .click({ force: true })

    cy.wait("@delete")
    cy.get('@list').should('have.length', 3)
  })
});

@jennifer-shehane what was your solution for this issue again?

This same issue:

/// <reference types="Cypress" />

before(() => {
    // Check if we have connection with backend
    // Stop executing tests if we failed
    cy.request({
        method: 'GET',
        url: 'api/version'
    })
})

beforeEach(() => {
    cy.restoreLocalStorage();
})

afterEach(() => {
    cy.saveLocalStorage();
})

describe('Section1Overview', function () {
    before(() => {
        cy.login()
        cy.server()
        cy.route('GET', 'api/Assessment/loadQuestionnaire').as('loadQuestionnaire')
        cy.visit(Cypress.env('employee_form'))    // This is first Visit!!
        cy.wait('@loadQuestionnaire')
    })

    require('./Section1/Page1.js')
})

.vist() and .wait() didn't work for me, error logs on cypress suggested using .request() instead which works fine.

cy.server(); 
cy.request('/api/path').then((xhr) => {
  console.log(xhr.body)
})

@macarenagil No one ever produced a reproducible example that the Cypress team could run to recreate this, so this issue was closed.

Some advice if your cy.wait() is not resolving.

  • Make sure cy.server() and cy.route() are defined BEFORE you cy.visit() or BEFORE you do the action that will cause the route to go out.
  • Are you waiting for a FETCH response? We don't fully support this yet. https://github.com/cypress-io/cypress/issues/95
  • Make sure to defined the method on the cy.route() if needed, it automatically only listens for GET requests by default.

@jennifer-shehane Very helpful! What resolved the issue for me was specifying the type of request ie. cy.route('POST', 'api/add_comment').as(addComment) . This can actually be found under cy.route()
Route default

Good day. Having same issue. As I have noticed it seem to be with GET method requests.
Could you please direct me if I'm doing it somehow wrongly?

Screenshot:
image

Test:

describe('Test wait issue', function() {

    const XHRTimeOut = 1000; //1 sec

    beforeEach(function () {
        cy.server({ urlMatchingOptions: { matchBase: false, dot: true } });
        cy.route({method: "GET", url: '**/complete/search**'}).as('apiCall');
    });

    afterEach(function () {});

    it('Wait issue test', function () {
        cy.visit('https://www.google.com/');
        cy.wait(Array(1).fill('@apiCall'), {timeout: XHRTimeOut});
    });

});

@PavelBuda I can see how the request is being made, but never resolving in the Command Log and never being found in the await. I actually don't even need the wait to exhibit this issue. The request is just never resolving on its own.

The complete/search request isn't always made on refresh or run of the tests - so you may have to refresh to see it.

it('Wait issue test', function () {
  cy.visit('https://www.google.com/')
})

Screen Shot 2019-07-25 at 3 33 17 PM

Edit: I think this issue is different than the one originally described. The original issue involved the XHR actually responding but never being registered by cy.wait().

Thank you for response. Yes have noticed that this was a bad sample.
How ever a real sample, that I may share, on video. It's the root issue that I have, and it seems like floating issue. One video which has wait(@alias) structure and have this issue.
Second video doesn't have an issue if I use wait(5000), which is not prefered at all, even if it's still a solution.

Issue with alias wait
Working with time wait

Sample code used:

 beforeEach(function () {
...
        cy.server({ urlMatchingOptions: { matchBase: false, dot: true } });
        cy.route({method: "GET", url: '**/ajax/**'}).as('ajaxRequest');
...
    });

it('Case 1", function() {
...
        cy.visit('/main/report.php?getsmily-id=reportwebsite00');
        cy.wait(Array(7).fill('@ajaxRequest'), {timeout: 5000});
...
    });

Possible workaround:

I've noticed that issue occurred if I use native browser refresh (cmd+r)
if I do test restart with Cypress provided stop/restart button cy.wait and pageload seems to work properly

@PavelBuda The issue seems to be caused b/c when you use the wait(ms) you are ensuring that all routes are waiting the full 5s regardless of whether the response has been received or not. Without the explicit wait, you are not guaranteeing that all of your routes will be ready at the same time. Have you tried extending the route wait time in the cypress.json? Try extending the request/response to see if it helps: https://docs.cypress.io/guides/references/configuration.html#Timeouts

When I am running single spec file , then this works fine ( All cases passed which consists @wait). But when I run multiple specs file , then @wait starts failing for 2 test cases where wait is used..

CypressError: Timed out retrying: cy.wait() timed out waiting 30000ms for the 1st request to the route: 'example'. No request ever occurred.

cy.route(
  "PUT",
  `/proxy/example`
).as("saveDrawer");
cy.get(selectors.saveDrawer).click();
cy.wait("@saveDrawer")
  .its("status")
  .should("eq", 200);

@william-deckard

The issue seems to be caused b/c when you use the wait(ms) you are ensuring that all routes are waiting the full 5s regardless of whether the response has been received or not

When I use wait(ms) with 5s there is no issue, and such time limit 5s is only due that I want to be sure that all requests were processed in this time. While when using wait(@alias, {timeout: 5000}) is expecting that each of routes have not exceeded time with 5s?

Without the explicit wait, you are not guaranteeing that all of your routes will be ready at the same time.

I supposed that wait logic with aliases is supposed to monitor if all matching routes have been found and got response (which is the case when not all responses are at the same time). Or I misunderstand the logic which it should be working?

Have you tried extending the route wait time in the cypress.json?

I'm extending the wait time directly form wait(@alias, {timeout: 5000}) (tried with
30000 = 30 sec and still it doesn't matter, as I already see the requests got responses from left menu test steps, but the wait trigger didn't worked)

Try extending the request/response to see if it

Would try, don't really remember if not already tried this, but it supposed to be just default values as override directly in command wait(@alias, {timeout: 5000})?

@PavelBuda According to the documentation "Once Cypress detects that a matching XHR has begun its request, it then switches over to the 2nd waiting period. This duration is configured by the responseTimeout option - which has a default of 20000 ms." Your error indicates that Cypress found the xhr request but is only waiting 5000ms according to the error... This is looking like a bug to me.

I took a look at the network request docs: and saw that doing something like this:

cy.wait('@apiCheck').then((xhr) => {
  assert.isNotNull(xhr.response.body.data, '1st API call has data')
})

cy.wait('@apiCheck').then((xhr) => {
  assert.isNotNull(xhr.response.body.data, '2nd API call has data')
})

cy.wait('@apiCheck').then((xhr) => {
  assert.isNotNull(xhr.response.body.data, '3rd API call has data')
})

may be useful for debugging the routes. Although this isn't the prettiest, may help in diving into each xhr request as Cypress is seeing them and see if anything funky is happening that isn't when using explicit wait times. Actually, I have even put my cy.waits in a for loop before when I had a dynamic number of calls and wanted to account for them in one test. Perhaps this would be a workaround for you.

for (let numOfAPICalls = 0; numOfAPICalls < 7; numOfAPICalls += 1) {
        cy.wait(@aliasRoute) }

This is supposed to be taken care of by Cypress when passing an array of routes like you are currently doing but if it is indeed a bug these might be better interim solutions then explicitly waiting.

@william-deckard
Thnx for suggestions sounds like a good point to debug it.

@william-deckard

Cypress.Commands.add("waitAliases", function (routeAlias, count, timeout) {
    for (let i = 0; i <= count - 1; i++) {
        cy.wait(routeAlias, {timeout: timeout}).then((xhr) => {
            console.log((i + 1) + ":   ", xhr.response.body, typeof xhr.response.body);
        });
    }
});

Is nicer, but still some times the issue still appear:
In console.log I see that there were no response for some routes (console.log((i + 1) + ": ", xhr.response.body, typeof xhr.response.body); is not triggerd).
But at the same time I see in network tab, that all routes have 200 status code and have already returned response.

So the issue seems still to be there :(

Good day.
Wanted to ask if there is any status on this issue?

Meanwhile as I understand the issue still exists, wanted to share with a nice package which may be a workaround: cypress-wait-until

I've been having this issue for some time, for me it is non-deterministic. This could be an issue with my code structure, as I have nested waits and am chaining .then() callbacks.

I have three endpoints I am trying to cy.wait() on in sequence, and they are dependent on each other so I cannot explicitly declare each wait, I have to use loops. Say the three endpoints are getA, getB, getC, the flow is along the lines of:

  1. cy.wait(@getA)
  2. .then() for n items in the payload from @getA, cy.wait(@getB) n times
  3. .then() for n items in the payload(s) from @getB, cy.wait(@getC) n times

This is all done in a before() hook as I want to compare data returned from live APIs with what is displayed on screen.

Like @PavelBuda I am seeing all the xhrs come through on the left in the Cypress GUI, but the timeout still occurs, usually on the 2nd or 3rd cy.wait(@getC).

Hi!
I've got the same issue with cy.wait(@alias). Tried a lot of ideas, but nothing.
1) The main problem, fot GET request - it's ok more or less.
for POST - trouble :(
2)I've got XHR responses :
Screen Shot 2019-09-04 at 11 46 39
3) in my test:
Screen Shot 2019-09-04 at 11 56 35

This POST request responses authtoken and redirectURL, which one I wanna use after in cy.visit.

But my test failed at step cy.wait
Screen Shot 2019-09-04 at 11 52 32

What is wrong?

@anikolaieva-IP looks like you’re waiting after the XHR has been fired. Can you confirm timing?

@jvrankul it’s difficult to imagine exactly what you are doing. When you say dependent, are you saying your application checks the payload of the first request before firing the next? One thing that I want to stress which seems trivial is check your routes compared to the actual XHRs in the browser to make sure they match. Then, make sure you are timing your waits so that they come before your triggers.

Hello,

I'm facing the same issue with latest Cypress version. Basically put, there seems to be an inconsistency with the XHR loading wait, in a sense that XHRs are loaded, afterwards the test waits for XHRs to load=> timeout. This does not happen all the time, but rather once every 3-4 cycles, case when waiting after XHRs are fired.
Relevant screenshots:
Screenshot_5
Screenshot_6

@anikolaieva-IP looks like you’re waiting after the XHR has been fired. Can you confirm timing?

@william-deckard yes, this POST request going to third-party service and gives me response with variables.
timing between 13500 to 17200 ms

Maybe this one helps somebody else but I encountered similar issue when waiting for a GET request. The test looked something along the lines:

  it('should request list', () => {
    cy.server().route('GET', '**/list').as('getList');
    requestList(); // this one fires '/list' API request
    // wait for API request to finish
    cy.wait('@getList').its('status').should('be', 200);
  });

This one always timeouted. The problem was that API request to GET /list was sent with query params, for example ?userId=1&category=10. As soon as I changed route definition as follows:

cy.server().route('GET', '**/list?**').as('getList'); <- do not overlook this part ?** in url

timeouts vanished and everything worked like a charm. So the outcome is if you are listening to GET request with query params include the ?** part at the end of the route URL.

After months I hoped it would be fixed. Why is this still open? :\

It looks like if you do not have a cy.visit in a test cypress will not know whether the request is resolved or not e.g if you have cy.visit in before function cypress will only be able to check status for the first "it".
For the rest "it"s requests will never be shown as resolved in cypress

I got the same issue, here's the code where the wait happens and fails:

it("loads", () => {
  cy.server();
  cy.route("/*").as("getRoot");
  cy.visit("/"); //Changing this to /* doesn't help
  cy.wait("@getRoot");
  cy.contains("Welcome");
  if (cy.contains("Logout")) {
    cy.get("[data-test='Logout']").click();
  }
});

I've tried reading everything here, and sorry if I am being repetitious, but I have figured out a _no-good-terrible way_ to solve this for our use case.

Essentially it appears that the first it in our spec will not capture or log any XHR requests. This means waits fail, as well as I do not see any (xhr) PATCH 204 /... messages in log. However, subsequent it statements all work as intended. The stupid solution is to put a noop it statement first before any of the real ones, and everything works perfectly, every time.

Sample code that causes the issue:

before(function() { // cy.visit happens via a command here...I know, I know });
beforeEach(function() {
  cy.server();
  cy.route({
    method: "PATCH",
    url: /diagram-service\/diagrams/,
  }).as("diagramPatch");

  cy.anotherCommand();
});

it("needs this to be able to wait for xhr requests", function() {
  assert.isTrue(true);
});

it("does the first test", function() {
  cy.someCommandThatYields()
    .then(function(v) {
      if (v !== 0) {
        cy.someCommandThatDoesThePatch();
        cy.wait("@diagramPatch");
      }
  });
});

Without the first it block, the wait never succeeds despite the network call showing in the network tab. The routes section in the side panel also shows no recorded responses.

We started having this issue after a minor refactor which eliminated the first it statement by combining it with the second to follow Cypress's "don't write unit tests" mentality. I didn't realize that was the cause until I figured this out, but now it works every time, without fail.

I had another idea after posting this, it turns out you can eliminate the noop it block by nesting the failing it block inside of a describe:

before() // same as above
beforeEach() // same as above

describe("The first test, function() {
 it("does the first test", function() {
  // same as above
  // WORKS EVERY TIME
});

Hello

That not works for me
And I confirm the server receive the request and send response

  it('clicks on "Recevoir mon devis"', () => {
      cy.server();
      cy.route('POST', `http://localhost:9030/api/public/website/checkout-quote`).as('order')
      cy.contains('Get my quote').click()
      cy.wait('@order').then((xhr) => {
          console.log(xhr)
      })
        .its('status')
        .should('eq', 200)
  })

Screenshot 2019-11-17 22:16:22

if you are using fetch this shoud work:

// use `Cypress` instead of `cy` so this persists across all tests
Cypress.on("window:before:load", win => {
  win.fetch = null;
});

Link: https://github.com/cypress-io/cypress/issues/95#issuecomment-347607198

It looks possible that the initial nested describe block may not hold up. New day and the issue is back with the same code. I added back in it("starts!", () => {}); as the first it inside of the primary describe and that makes it work again...for now.

I am experiencing the same issue. Any updates?

I had another idea after posting this, it turns out you can eliminate the noop it block by nesting the failing it block inside of a describe:

before() // same as above
beforeEach() // same as above

describe("The first test, function() {
 it("does the first test", function() {
  // same as above
  // WORKS EVERY TIME
});

It worked me but just for one time, then never again.
This is crazy. I don't know what happened, my test were working correctly, and after just 2 weeks holiday they are broken. Tried to downgrafe Cypress, use functions insteads of arrow functions, nothing worked. :(

It worked for me after implement below step

a) I mentioned cy.route command in beforeEach() section
b) I mentioned cy.wait(xhr..) in the it block at the place where assertion was needed.

Timeout issue occurs when cy.route is mentioned just before cy.wait

For me issue was solved after two steps:

  1. Add to my cypress.json config this value (It's could depend on you request timing)
{
  "requestTimeout": 10000,
}
  1. My request includes additional parameters like /pages&limit=10&offset=0 etc. I've tried to listen like cy.route('GET', '/pages').as('getPages'); after I added exact parameters it's working cy.route('GET', '/pages&limit=10&offset=0').as('getPages');

I have encountered this issue.

I have 35+ tests. Every test are built on the same pattern of waiting requests. One of all the tests does not work.

Samples of the routes defined before everything.
image

The test
image

Here you can see that the route fetchUsers has been answered (200 with a response).
image

In this particular case, the route should already be matched since it's waited 2 times and has been queried 3 times.

If I wait two times the fetchUsers query at at first, the second wait will throw for the same reason...

The most stunning things is that if I restart the test many times, sometimes it passes...

There is no case ever where the cy.wait() would say there is no response in my test.
I insist, i got many tests doing the same kind of things and this is the only one doing this error

I can't give you the code of the test since there are quite bigs but I can affirm that cy.server() is the first line to be called, the routes are being defined just after the cy.server() line. cy.visit() occurs after the route definition.

Hello,
I have the same issue :/
To solve this, I add cy.wait(500) after cy.visit() and before cy.wait(xhr..).

I know this is not a clean option, but this issue was open a year ago and I still waiting a fix.

@toto-le-motard Very interesting, I'll give that a test too, that makes sense why this sometimes just pops up in old tests, if they were written to have enough steps prior to the first cy.wait(xhr...) then they would work, otherwise they might be under whatever astronomically constant time is necessary to avoid the issue.

Someone test it with Cypress 4.0.X?

Hello, I have the same issue and I solved by using full API URL
example:

cy.server()
cy.route({
  method: 'GET',
  url: `https://myapi.com/user/profile` // or use env variable via `${Cypress.env('BASE_API')/user/profile}`
}).as('userProfile')

cy.visit(Cypress.env('HOST'))
cy.wait('@userProfile')

Hope this helps.

@biigpongsatorn does not works for me :/
@Saibamen I use the version 4.0.0

Also not working for me.
v 4.0.1

Hello everyone! Still facing the same issue as of v4.0.1.

I did find out a way to make it run properly since my last comment, although keep in mind, this is more of a _workaround_. Basically put, using cypress-plugin-retries, I can effectively trigger the spec to retry in case the test fails because of the faulty XHRs and can attempt to wait for the XHRs to load correctly. In my case it works fine at most after 2 retries, because the troubling XHR requests happen during a login scenario, which shouldn't impact any other step after those commands are executed (type username/password etc. then wait for XHRs to load). Hopefully this helps you at least to some extent!

If you are using the option parameter to define the route then make sure to include the response parameter in there even if it is to be set to blank. That resolved my issue with the wait happening after the actual call is done.

This is getting really frustrating for us. We do not receive this error every time and actually only when running the tests in docker. We use drone.io for our CI and the official cypress-docker-image (cypress/included:4.0.1).
All our tests start with visiting the page and cy.wait()-ing for our translation file to be loaded. Locally the tests run fine, in the CI they fail randomly.

To solve this, I add cy.wait(500) after cy.visit() and before cy.wait(xhr..).

I tried this as well, test stability went up a little bit, but I still have failing tests.

Someone test it with Cypress 4.0.X?

Just upgraded yesterday. Does not make a difference.

I cannot understand how this attracts so little attention by the team. For us this currently makes cypress useless, as test-results are completely inconsistent.

v4.0.2 still gives this error CypressError: Timed out retrying: cy.wait() timed out waiting 5000ms for the 1st request to the route: 'doLogin'. No request ever occurred.

Hopefully this helps some of you as it did help me: #1716 comment.

Hello, I have the same issue and I solved by using full API URL
example:

cy.server()
cy.route({
  method: 'GET',
  url: `https://myapi.com/user/profile` // or use env variable via `${Cypress.env('BASE_API')/user/profile}`
}).as('userProfile')

cy.visit(Cypress.env('HOST'))
cy.wait('@userProfile')

Hope this helps.

Same. Was getting the error while the request was being made. As soon as I used the full URL it worked..

Much like others I'm getting nailed by this same issue where cy.wait(aliases) triggers a timeout by random. Hopefully we can land a fix here soon

If this can help, it seems that my timeout was due to the clock setting in my beforeEach for a test suite: cy.clock(new Date('2020-02-20T09:00:00Z').getTime());
Once it's removed, no more timeouts. Not sure how to interpret this

I was also facing the error but I fixed it. by default cy.route showing Get method and if you have post method API and will not explicity metion post then you will get this error message.

Here is the syntax for post API routes:

cy.route('POST',"Your API post URL").as("alice")

Note: Make sure that route is work as a listener you must have to define it before performing the action and then you will use it as wait.

I am also facing this issue on my app for alias routes assertions for POSTs in my Cypress tests, though strangely this timeout only happens in CircleCI. I tried the various suggestions to no avail.

I'm using fetch in my Next.js app, so in Cypress support/index.ts, I use the following code to use the unfetch polyfill (to convert fetch requests to XHR, so I can spy on the XHR in Cypress):

Cypress.on("window:before:load", win => {
  fetch("https://unpkg.com/unfetch/dist/unfetch.umd.js")
    .then(stream => stream.text())
    .then(response => {
      (win as any).eval(response);
      (win as any).fetch = (win as any).unfetch;
    });
});

Using Cypress 4.3.0 with Electron 80 browser. Also, probably not too important, but the app is using Next.js + TypeScript + MaterialUI.

I was able to create to create a small repo that reproduces this issue. I tried to have the same setup/dependencies/etc as my app. Although in this repo, it is failing both locally (MacBook Pro 16, ~50% of the time) and CircleCI (all the time), vs. my project which is just CircleCI failing.

Test File: https://github.com/dphang/cypress-test/blob/master/cypress/integration/test.spec.ts
Repo: https://github.com/dphang/cypress-test
CircleCI builds: https://app.circleci.com/pipelines/github/dphang/cypress-test

I didn't see a repro repo posted yet, so I hope this is helpful to the team to debug what's happening? Thanks!

EDIT: created new issue here https://github.com/cypress-io/cypress/issues/7207 since this actually seems like a different problem.

I'm facing the same issue. That's how the code basically looks like in my case:

Cypress.on('window:before:load', (window) => {
  window.fetch = null;
  (window as any).eval(response);
});

describe('Tests', () => {
  const cookie = Cypress.env('myCookie');

  before(() => {
    cy.setCookie(cookie.name, cookie.value);
  });

  after(() => {
    cy.task('myTask');
    cy.clearCookies();
  });

  beforeEach(() => {
    Cypress.Cookies.preserveOnce(cookie.name);
  });

  it('should do stuff, () => {
    cy.server();
    cy.route('POST', '/my/first/url').as(
      'firstUrl',
    );
    cy.route('/my/second/url').as('secondUrl');
    cy.route('/my/third/url').as(
      'thirdUrl',
    );

    cy.visit('/home');
    cy.get('my-btn-locator').click({});

    cy.wait('@firstUrl');
    cy.wait('@secondUrl');
    cy.wait('@thirdUrl', { timeout: 60000 });

    // ... More code

  });

Then I get CypressError: 'cy.wait()' timed out waiting '60000ms' for the 1st request to the route: 'thirdUrl'. No request ever occurred.

@jennifer-shehane

@ohad2712 looks like you are expecting 3 api calls to happen async on button click. Have your tried waiting for all of them in one wait? You might be running into race condition trying to wait for three routes separately like that.

https://docs.cypress.io/api/commands/wait.html#Syntax

@william-deckard those api calls are actually supposed to be called one after the other, and not asynchronously. The @firstUrl should be called (and it does), and then the @secondUrl should be called, but then the @thirdUrl should be called and then there's the error I get.

Getting this issue randomly as well. In the recording I noticed that it immediately fails, even if it claims that it timed out after 5000ms 🤷
Note: I only get this in CI, can't reproduce locally

I'm facing the same issue. That's how the code basically looks like in my case:

Cypress.on('window:before:load', (window) => {
  window.fetch = null;
  (window as any).eval(response);
});

describe('Tests', () => {
  const cookie = Cypress.env('myCookie');

  before(() => {
    cy.setCookie(cookie.name, cookie.value);
  });

  after(() => {
    cy.task('myTask');
    cy.clearCookies();
  });

  beforeEach(() => {
    Cypress.Cookies.preserveOnce(cookie.name);
  });

  it('should do stuff, () => {
    cy.server();
    cy.route('POST', '/my/first/url').as(
      'firstUrl',
    );
    cy.route('/my/second/url').as('secondUrl');
    cy.route('/my/third/url').as(
      'thirdUrl',
    );

    cy.visit('/home');
    cy.get('my-btn-locator').click({});

    cy.wait('@firstUrl');
    cy.wait('@secondUrl');
    cy.wait('@ThirdUrl', { timeout: 60000 });

    // ... More code

  });

Then I get CypressError: 'cy.wait()' timed out waiting '60000ms' for the 1st request to the route: 'thirdUrl'. No request ever occurred.

@jennifer-shehane

what is the method of your second and third URL? Can you just comment second and third URL and try that is it first URL wait is working for your or not?

@ArshadIram I'm not sure I get what you mean, but I'll try to answer as detailed as I can.
So @firstUrl is obviously for a POST request, while both @secondUrl and @thirdUrl are GET requests.
The one url request which is flaky is the @thirdUrl, and I can comment the @secondUrl before that, but it doesn't change the flakiness of @thirdUrl. I cannot comment the first one because this is the request that eventually leads to the other two requests.

There is a difference between syntax of your second and third URL.

cy.route('/my/second/url').as('secondUrl');
cy.route('/my/third/url').as('thirdUrl',  );

I mean what is the purpose of this comma ","? @ohad2712

Just a linting stuff. You can just ignore it.
The code compiles, run and even passes some times, but in the CI it usually fails from the reason I've explained in my first comment.

I'm having same issue. All other tests made with cy.route() work, two specific tests are failing. Checked against all other tests and found no difference between them. Also tried solutions proposed through this issue, but it didn't work out.
cy.server() and cy.route() is set in beforeEach() and I'm creating a new account for company's site.

cy.wait("@createAccount").then(xhr => {
      assert.equal(xhr.status, 400);
      expect(xhr.response.body).not.to.be.null;
      expect(xhr.response.body.error).not.to.be.null;
    });

Has anyone find a solution that works for it?

@ohad2712 When you rely on requests triggering each other in that manner, it is more complex than simply calling Wait before all of them. Can you provide some example code. I imagine you need something from the payload of the response of the 1st request for the next requests. If that is the case, you should try waiting for the 1st, perform test on the response, then wait for the next calls.

A different solution entirely is the only check the 1st request, then perform checks on the behavior of your application instead of checking the request. For example, suppose I wanted a button to be the color specified in the payload of my last request. What you could do is check that your button has in fact changed color. This would also confirm that the appropriate request was triggered and returned. If you read Cypress docs, their best practices are more focused on application behavior testing anyway.

Also, I should note that I believe the timeout that you are passing is the timeout for the request to come back, not for waiting for it to happen. I should be fact checked here.

I leave all request alias to beforeEach function, and the error is gone.

 beforeEach(() => {
    const baseURL = 'Your base URL';

    cy.server();
    cy.route({
      method: 'POST',
      url: `${baseURL}/submit`,
    }).as('submit');

    cy.route({
      method: 'GET',
      url: `${baseURL}/getProduct`,
    }).as('getProduct');

    cy.visit('/home');
  });

And then when i use it:

cy.wait('@getProduct', { timeout: 6000 });

Hope it help.

@ducpt2 tried that one, doesn't work. When running through command line, never works. For UI, sometimes. Tried to change timeout for more than 20000, and got no different results.
Only difference I saw so far, is that changing test positions - making the ones that use cy.route and cy.wait() first, makes them fail less.

@ducpt2 tried that one, doesn't work. When running through command line, never works. For UI, sometimes. Tried to change timeout for more than 20000, and got no different results.
Only difference I saw so far, is that changing test positions - making the ones that use cy.route and cy.wait() first, makes them fail less.

20000 is for response time, not for the request to happen. You should put performance times before your wait and before your request and and post results. performance.now()

I was so upset this wasn’t solved yet, and unable to use while using globs that I sent a tweet over here: https://twitter.com/char_greenman/status/1273282685797126146?s=21

Should note, manpower isn’t the issue: https://www.crunchbase.com/organization/cypress-io#section-overview

^ this bug should be your number 1 priority

@CharlieGreenman we have two upcoming releases that _may_ address this problem but we need a reproducible example to be certain.

If you are 100% blocked on this issue, please create a reproducible example in a repo to show us what scenario is failing. With a reproduction, we can confidently triage and fix this issue.

@CharlieGreenman we have two upcoming releases that _may_ address this problem but we need a reproducible example to be certain.

If you are 100% blocked on this issue, please create a reproducible example in a repo to show us what scenario is failing. With a reproduction, we can confidently triage and fix this issue.

@JessicaSachs trying to think through how I can do this. To reiterate point made on Twitter. Proprietary and internal apis, but I can potentially use open qsource apis to get this going. To be honest it’s probably going to take 1.5 hours of my time. I will not get paid for this work, so realistically, being that not 100% blocked, I am not going to work on it. If cypress would like to accommodate me for time spent recreating bug, [email protected] would be the right place to send something.

(Creating an extra 10 network requests that might break, due to somewhat fragile nature of write down complete, url, yes.) Oy! Software is rough sometimes

please create a reproducible example

Sorry, but this text should be only placed in bugs where we do something strange with Cypress, but not on bugs where it is 85 comments and 52 participants...

This looks like noone from Cypress Team is using this software in real life...

Similar to this comment https://github.com/cypress-io/cypress/issues/695#issuecomment-553047455 for bug reported in 29 Sep 2017 (sic!) with 113 comments and 69 participants

If you want help with prioritizing bugs to be fixed, here is your issues sorted by most commented: https://github.com/cypress-io/cypress/issues?q=is%3Aissue+is%3Aopen+sort%3Acomments-desc

Clear and simple way to show what real users want to have in Cypress most.

Here is this same sorting, but only with label bug: https://github.com/cypress-io/cypress/issues?q=is%3Aissue+is%3Aopen+sort%3Acomments-desc+label%3A%22type%3A+bug%22

@JessicaSachs just to reiterate point of @Saibamen but from a slightly different angle. This is a serious bug :)

Right now, no one operating at this level(ie software architect) is going to reproduce issue. So, given current situation this will remain a bug. @JessicaSachs any idea how given the dynamic, we can get someone to spend time to reproduce bug?

^ in short the issue is that when stubbing a url like ‘v1/users**’ and that request happens two or more times in succession, and you wait for aforementioned url twice one after another, then it will skip the 2nd periodically causing the entire test to fail. The weird part about it, is that it’s sporadic. I was once doing this with 4 of them. Sometimes would be 2nd that would fail, sometimes the 3rd, sometimes the 4th, until I just created absolute urls for each without stubbing. I though for real should go to be now. It’s 1:50am in the JLM

Honest, if could just pass along file with stubbing logic, it would probably be relatively easy to find bug. @JessicaSachs that work? Feel free to pass along url of stubbing logic file - that is logic for stubbing a route eg cy.server , cy.route(‘v1/user**’) etc

I would love to give you a 100% reproductible error. But this happens to me only when I run all of the project tests. It happens on 2 tests over 103 now. It does not fail when it runs within the suite. Since I can't give the 103 tests and access to our application, even if I could isolate a test, you would say that there is nothing wrong with it. Which is true, unless circumstances...

One thing to note is that it was happening to one other test. I refactored the code and the test for a feature. Since, the test succeed all the time. The xhr scheme is totally different and seem to be more compliant to what cypress is expecting. But still, I don't understand in what way.

We recognize that this is very frustrating, especially since Cypress strongly advocates using cy.wait() for routes as a best practice. We very much want to fix this.

That being said, we regularly read the comments and we've re-reviewed all of the comments in this thread and there has not been a single reproducible example given. Without this, we have no path forward with identifying the cause of this issue and fixing the issue.

We use Cypress ourselves to test all of our products, every piece of the Test Runner, the Dashboard, and over 30 example repos. Since Cypress can be used to test everything on the internet, there are infinite variables that could contribute to a specific bug. We have not encountered this issue ourselves, so there is likely something outside of our usage that affects when this happens.

Please provide a reproducible example

Having a reproducible example is vital for us when narrowing down the cause of an issue among the infinite contributing variables available.

We really want to address this issue. To do that, we need a fully reproducible example provided that we can run on our machines.

If you have a reproducible example that you cannot share publicly, you're welcome to email us at [email protected] to share privately.

Related Issues

There are a couple of other issues I'd like to note as reproducible bugs around cy.wait() never resolving. If you see your issue fits within one of these, please refer to the respective issue:

General tips for cy.wait()

There have been some cases mentioned in this thread where the issue was solvable by rewriting how the tests were written.

We definitely see room for improvement here in our documentation and our API in general. We understand this can be frustrating and we believe it's our responsibility to help when a concept is commonly misunderstood in our product. We are working on improving the APIs around network requests overall here. https://github.com/cypress-io/cypress/pull/4176

  • Make sure cy.server() and cy.route() are defined BEFORE you cy.visit() or BEFORE you do the action that will cause the XHR request to go out.
  • Are you waiting for a FETCH response? We don't fully support this yet https://github.com/cypress-io/cypress/issues/95 There are workarounds and an experimental fetch polyfill in v4.9.0
  • Make sure to define the method on the cy.route() if needed. cy.wait() automatically only listens for GET requests by default.
  • Double check the route's URL glob, that it will match the request you are waiting for. We use minimatch under the hood so you can check using Cypress.minimatch()
  • If you have any custom overriding code for requests or mix async code in with Cypress commands, make sure there is not an async issue that could introduce variability in your timings when waiting for responses. https://github.com/cypress-io/cypress/issues/7207

@jennifer-shehane thank you for jotting this down, you obviously put in time and effort. Just curious, what incentive would I have to create a reproducible example?

@jennifer-shehane is that it? I’m taking this to LinkedIn and I’m suggesting people not use Cypress. It’s a sham, everyone suggesting it and it doesn’t even work. So upset right now, especially with the burden being put on the community to produce examples. I can assure you, if I would have stuck with protractor I would be having a better time and getting these tests out quicker

LinkedIn post made here that expresses how I feel, and that hopes to bring more visibility to this issue: https://www.linkedin.com/posts/charliegreenman_cywait-always-gives-a-timeout-error-no-activity-6679349210942369792-Zxv5

thank you

@CharlieGreenman your "incentive" would be fulfilling your company's mission, and possibly the issue getting fixed. Thanks for the update @jennifer-shehane + @JessicaSachs

image

Last chance, money, final offer

On Thu, Jun 18, 2020 at 9:10 PM Ben Mitchinson notifications@github.com
wrote:

@CharlieGreenman https://github.com/CharlieGreenman your "incentive"
would be fulfilling your company's mission, and possibly the issue getting
fixed. Thanks for the update @jennifer-shehane
https://github.com/jennifer-shehane + @JessicaSachs
https://github.com/JessicaSachs

[image: image]
https://user-images.githubusercontent.com/33632286/85055417-1e82f900-b163-11ea-875c-fa886907a5e0.png


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/cypress-io/cypress/issues/3427#issuecomment-646224530,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/ACBE73KWQIRZ2OYTPWU6XZDRXJKAFANCNFSM4GWTWJ4A
.

>

All and only the best,
Charlie Greenman
Founder and UI / Compiler Architect

I should also add, the point of our mission is to help people. I'm starting to get the feeling that Cypress is the Theranos of end to end testing, and I want nothing to do with it. I made a post on LinkedIn, and instead, the entire team removed their tag, instead of having the courage to face the professional world. Money is no longer an option, I am no longer recommending to clients to use Cypress. Thank you.

Will revisit in a year and a half and keep using for client already entrenched with. Enjoy this Tiktok in the meantime https://vm.tiktok.com/JJkERSV/

@CharlieGreenman Very disappointed to see your comments and attitude towards the Cypress team especially now that you have gone public on a social media platform to cry 😢 .

I am not going to work on it. If cypress would like to accommodate me for time spent recreating bug, [email protected] would be the right place to send something.

What. a. joke.

You run a company called "Razroo [that] is committed towards contributing to open source" but you are asking to be compensated...I have the strong feeling you are using the "free" version of Cypress. If you weren't you would be contacting Cypress through more direct customer --> company communications.

The real reason you don't provide a 100% reproducible example? Because you are technically incapable. I hope your clients come to this post you linked to so that they can see your incompetence.

Anyway, I must add that I use Cypress in the wild and am not having any issues waiting on routes to return appropriately. Congrats to @brian-mann and his team for creating such an amazing testing tool.

ok, i respect that. I will say this issue has been going on for a year, and I successfully got everyone's attention

@TheCaffinatedDeveloper also, just a quick question. You joined Github 11 minutes ago, right? You sure you're not a bot? Also, I'm not using Cypress actually as of today. Giving away something for free, that takes away the time of others, I have no tolerance, I'm sorry, and this is where this comes from. Also, my company literally just launched it's website this month. I've been hustling nights and weekends to try and make it happen, and I appreciate the hustle. For that reason, I'm super sensitive to my time being taken up, and probably just more sensitive in general.

We’d like to please remind everyone to keep discussion relevant to the issue of the originally opened issue. Comments that are helpful:

  • Explaining the issue you are encountering relating to cy.wait() not resolving for routes
  • Providing a reproducible example of the issue.

This is not the place for a larger discussion of Cypress as a whole or the open source community. There are plenty of other online forums to accommodate this type of discussion.

I’d also like to remind everyone of the Code of Conduct which applies directly to conversations in these issues. https://github.com/cypress-io/cypress/blob/develop/CODE_OF_CONDUCT.md

We would like to keep the discussion open, as these threads can been very helpful to others encountering the same issue and also the main line of communication Cypress has to receive bug reports.

But, in the event that off-topic discussion is not curtailed, we will lock issues to further conversation. We want to respect users time and notifications for those who are subscribed to the issue so they get relevant input only.

Just got done dealing with the exact issues above. I solved it by following the guidance of cy.server() and cy.route() first, followed by cy.wait(). Also, the key fix which I only see in https://docs.cypress.io/api/commands/route.html#Examples but is completely missing from https://docs.cypress.io/guides/guides/network-requests.html#Waiting is the idea of url globs. I suspect many others were doing what I did by following the network-requests doc and listening to url: '/api/' or something like that. instead do url: '/api/*'. The double star made everything work perfectly. hope this helps somebody else.

The definitive solution. If this does not work, there may be an error in your GET service.
`
cy.server();
cy.route({
URL: "URL...",
method: "GET"
}).as("tickets_count");

  cy.visit("http://localhost:5000/dashboard");

  cy.wait('@tickets_count');

  cy.get('@tickets_count').then(function (xhr) {
    console.log("xhr: ", xhr);
  });

`

I was having this issue too until I discovered I was trying to catch a request that was being done via http in the app but in my Cypress tests I was actually trying to catch it on the https protocol which was leading to a protocol mismatch. Maybe just check all the protocols match between what your app is sending and what Cypress is trying to catch in the cy.route()?

Just as a further bit of context on my setup:

I'm using Node Version 12.13.0, Chrome 84 and Cypress 4.11.0 on macOS Mojave 10.14.5.

I'm testing an app that makes requests to an API (one that I own and manage) so the relationship (locally) looks something like http://localhost:8080 makes requests to http://api.websitename.local/v1. I was trying to catch requests being made to https://api.websitename.local/v1.

Also I noticed some comments around making sure cy.server() is at the top of the file, along with the routes but to be honest that didn't have any effect after I changed the protocol mismatch, obviously it still needs to be defined before any requests are sent but it's placement otherwise doesn't seem important. However I would stick with what has been recommended already above about the placement of the cy.server() and cy.route().

Finally, cy.wait() should be defined after the request is made in the test but I think that is fairly obvious already?

I've only recently started to play around with Cypress and frontend testing in general so forgive me if I've missed something but I thought it was worth sharing anyway as it tripped me up, everything is working for me now.

Hi I am facing this issue quite often. Does anyone know the solution? My test-cases are flaky sometimes it fails and sometimes it passes, its soo irritating as the reason for choosing cypress was it's being non-flaky.

image

 cy.server();
  cy.route('POST', url).as('retrieveRecords');

  cy.findAllByText('Save & Exit', {
      timeout: 1000
    })
    .should('be.visible')
    .click();

  cy.wait('@retrieveRecords').its('status').should('be', 200);

Hello, I am also stuck with the same problem. I've read several posts about it and tried many different solutions, none worked.

Screen Shot 2020-08-06 at 2 10 23 PM

Screen Shot 2020-08-06 at 2 15 10 PM

What am I missing here? Thanks!

Requests made from the spec file using cy.request are NOT intercepted by cy.route. Only the requests made by the application are intercepted

Sent from my iPhone

On Aug 6, 2020, at 17:19, Rene Roger notifications@github.com wrote:


Hello, I am also stuck with the same problem. I've read several posts about it and tried many different solutions, none worked.

What am I missing here? Thanks!


You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or unsubscribe.

I have a similar issue, where I do something like this:

describe('My First Test', () => {

    beforeEach(() => {
        cy.server();

        cy.fixture('data-one.json').as('dataOne');
        cy.fixture('data-two.json').as('dataTwo');
        cy.fixture('data-three.json').as('dataThree');

        cy.route('GET', /api\/v1\/data-one/, '@dataOne').as('apiDataOne');
        cy.route('GET', /api\/v1\/data-two/, '@dataTwo').as('apiDataTwo');
        cy.route('GET', /api\/v1\/data-three/, '@dataThree').as('apiDataThree');
    });

    it('wait test', () => {
        cy.visit('/');

        ...

        // wait for all requests to fulfill
        cy.wait(['@apiDataOne', '@apiDataTwo', '@apiDataThree'], { timeout: 60000 });

        ...
    });
});

Not sure what I do wrong. Sometimes the test passes, sometimes it doesn't. The app I am testing is written in Angular 10 and cypress 4.12.0

Here is the error:

at cypressErr (http://localhost:9100/__cypress/runner/cypress_runner.js:170476:17)
    at Object.throwErr (http://localhost:9100/__cypress/runner/cypress_runner.js:170372:12)
    at $Cy.retry (http://localhost:9100/__cypress/runner/cypress_runner.js:162793:20)
    at checkForXhr (http://localhost:9100/__cypress/runner/cypress_runner.js:158775:18)
    at <unknown> (http://localhost:9100/__cypress/runner/cypress_runner.js:158776:29)
From previous event:
    at tryFn (http://localhost:9100/__cypress/runner/cypress_runner.js:163280:25)
    at whenStable (http://localhost:9100/__cypress/runner/cypress_runner.js:163321:13)
    at <unknown> (http://localhost:9100/__cypress/runner/cypress_runner.js:162839:17)

Not sure if the error I'm getting is the same as OP (in which case, let me know and I'll create a separate issue), but the error message itself is the same, so they might be the same issue.

If I try to stub a request and give it a String response, any cy.wait on that route will simply time out. If the stubbed response happens to be an Object, or Array, as the API documents those are the other two possible types, cy.wait will pick up the request just fine.

To note, the request _is_ being stubbed correctly, even when using a String. I can see this from the Routes section in the log, since it has a column listing the amount of calls for a given route. It's just cy.wait not picking up on it for some reason. Here an image of this:

ad7c39fa-a617-4a52-bbc9-1ca3f357907d

Here reproducible code as of v4.12.1:

it('cy.wait times out when response is a simple string', () => {
  cy.visit('https://zooplus.de/shop/katzen/katzenfutter_trockenfutter/purizon');

  cy.server();

  cy.route({
    method: 'PATCH',
    url: '/checkout/api/cart-api/v1/cart/*/set-article-quantity-command',
    status: 403,
    response: 'just a string',
  }).as('addToCart');

  cy.get('a[data-zta^="addtocartbtn_"]').first().click();

  cy.wait('@addToCart', { timeout: 10000 }).then((xhr) => {
    const data = {
      status: xhr.status,
      body: xhr.response.body,
    };
    cy.log(JSON.stringify(data));
  });
});

I haven't been able to test this yet (only tested with stubbed responses), but I believe _any_ request, stubbed or not, that happens to return just a string (so not something that might be a JSON, like an array or object response), will cause cy.wait to time out.

@Sighery I am able to recreate the situation you have described - where the response body being a string makes the stubbed XHR time out.

Repro

Cypress.on('uncaught:exception', () => {
  return false
})

beforeEach(() => {
  cy.visit('https://zooplus.de/shop/katzen/katzenfutter_trockenfutter/purizon')
  cy.server()
})

it('cy.wait times out when response is a simple string', () => {
  cy.route({
    method: 'PATCH',
    url: '/checkout/api/cart-api/v1/cart/*/set-article-quantity-command',
    status: 403,
    response: 'just a string',
  }).as('addToCart')
  cy.get('a[data-zta^="addtocartbtn_"]').first().click()
  cy.wait('@addToCart', { timeout: 10000 }) // fails, times out
});

it('cy.wait passes with response object', () => {
  cy.route({
    method: 'PATCH',
    url: '/checkout/api/cart-api/v1/cart/*/set-article-quantity-command',
    status: 403,
    response: {},
  }).as('addToCart')
  cy.get('a[data-zta^="addtocartbtn_"]').first().click()
  cy.wait('@addToCart', { timeout: 10000 }) // passes
})

Screen Shot 2020-08-21 at 2 22 41 PM

Does not repro

I wasn't able to repro this outside of that app however, so there must be something else involved

it('test cy.route()', () => {
  cy.server()
  cy.route({
    method: 'PATCH',
    url: /url/, 
    status: 403,
    response: 'foo'
  }).as('patch')
  cy.visit('https://example.com')
  cy.window().then((win) => {
    const xhr = new win.XMLHttpRequest()
    xhr.open('PATCH', '/url')
    xhr.send()
  })
  cy.wait('@patch')
})

Screen Shot 2020-08-21 at 2 31 03 PM

@jennifer-shehane You're right. I just tried with another store and I can't replicate this issue. Apologies, I should have tested more thoroughly.

Here code that does not reproduce with another store:

it('does NOT time out', () => {
  cy.visit(
    "https://www.amazon.com/AmazonBasics-Performance-Alkaline-Batteries-Count/dp/B00MNV8E0C"
  );

  cy.server();

  cy.route({
    method: "GET",
    url: "gp/page/refresh?**",
    status: 403,
    response: 'just a string',
  }).as("changeItem");

  cy.get("li.swatchAvailable").first().click();

  cy.wait("@changeItem", { timeout: 10000 }).then((xhr) => {
    const data = {
      status: xhr.status,
      body: xhr.response.body,
    };
    cy.log(JSON.stringify(data));
  });  // works just fine
});

I've tried to run both my reproducible code and yours on a new/fresh Cypress project, with no configuration other than the default, and it still times out. Can the website JavaScript affect the Cypress configuration in any way? What I find most strange in the reproducible code is that the Cypress interface, at the Routes section, recognises that a request happened and matched a route, but when I try to wait on that matched route it'll just time out, even though it happened and Cypress was able to match it.

@jennifer-shehane I am facing the same issue, I find it interesting that the issue doesn't happen for the first 'it' block in my context, but the issue will happen for all sequential 'it' blocks
for example, having


  context('Context', function () {
    before(function () {
      cy.login();
      cy.visit('page');
    });
    it('can do 1', function () {
      //do stuff 
     cy.server();
      cy.route('post', 'posturl').as('somethingPost');
      utils.click('Save');
     //below works 
      cy.wait('@somethingPost').its('status').should('eq', 201);
    });

    it('can do 2', function () {
      cy.server();
      cy.route('put', 'puturl').as('somethingPut');
      utils.click('Save');
     //this doesn't 
      cy.wait('@somethingPut').its('status').should('eq', 204);
    });
 });

If I altered the code above to have one 'it' block, then both waits will work as expected, below the code that worked


  context('Context', function () {
    before(function () {
      cy.login();
      cy.visit('page');
    });
    it('can do 1', function () {
      //do stuff 
     cy.server();
      cy.route('post', 'posturl').as('somethingPost');
      utils.click('Save');
     //below works 
      cy.wait('@somethingPost').its('status').should('eq', 201);
      cy.server();
      cy.route('put', 'puturl').as('somethingPut');
      utils.click('Save');
      cy.wait('@somethingPut').its('status').should('eq', 204);
    });
 });

something else I noticed was this.
this is the test body for the second 'it' block, after clicking the button, there was no XHR captured, although I checked the network and the request was fired.
image

this is the test body for the same code, but within the first 'it' block.
image

After debugging we found out that PaceJs was causing the issue, so if anyone is going through the same issue, just make sure that no interceptors are hooking to your xhr requests and causing this.

Any updates on this? We're experienced the same flaky problem when stubbing a request. Fails more often when running several tests and not only one.

Example

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

Got some time to investigate, at least a few hours.

I tried to upgrade to the 5.2.0 version. The problem still occurs.
Reading the comment of @rezres I tried commenting the interceptors. No change at all.

It still happens "randomly" when running multiple tests sequentially.
It does not happen if there is only one xhr sent and waited at a time.
It can happen if there is multiple xhr but only one wait. It can happens when waiting multiple times for the same xhr ( cy.wait([q1,q2,q3]) ).

I can't find anything to be sure to reproduce. I can't find anything that the application is doing and is messing with cypress xhr listeners.

Any updates on this? I've the same problem executing the integration tests in AWS CodeBuild. Even if my server receives the API call, Cypress raises this error.

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

I'm using Cypress version 4.12.1 but the same error is raised if I try the version 5.2.0.

Try to force match almost everyting except for your url keyword, this worked for me after many hours struggling.

cy.route({
        method: 'POST',
        url: '**/key_word/**'
      }).as('alias');

Still do not know why this was happening, my url was exactly the same as the route one.

After debugging we found out that PaceJs was causing the issue, so if anyone is going through the same issue, just make sure that no interceptors are hooking to your xhr requests and causing this.

This is correct. Is there any way that we can use cypress and pacejs in the same project?

Try to force match almost everyting except for your url keyword, this worked for me after many hours struggling.

cy.route({
        method: 'POST',
        url: '**/key_word/**'
      }).as('alias');

Still do not know why this was happening, my url was exactly the same as the route one.

I tried this but unfortunately, it's not working. I'm getting the same error:

CypressError: `cy.wait()` timed out waiting `5000ms` for the 1st request to the route: `personalData`. No request ever occurred.

I have the same problem :
cy.server() cy.route('http://192.168.0.209/saas/**').as('school') cy.wait('@school').then()
image

I have managed to find out that cy.wait timed out when happends "(new url)" events.
My project has logic that changes url (history replaceState) after click on a button. Also click triggers a POST request.
If i comment replaceState logic - POST request succesfully captures. If not cypress logs (new url) and not captures that request

@jianjiming looks like you struggling the same "change location" issue

Update: i have removed location assert. And cy.wait now works!

        cy.location('pathname').should(
            'eq',
            '/clients(filter:%F0%9F%94%96/%7B%22-735573861%22:%22%7B%5C%22pageNumber%5C%22:1,%5C%22pageSize%5C%22:10%7D%22%7D)',
            {matchCase: false},
        );

That style also causes a problem

        expect(window.location.pathname).to.be(
            '/clients(filter:%F0%9F%94%96/%7B%22-735573861%22:%22%7B%5C%22pageNumber%5C%22:1,%5C%22pageSize%5C%22:10%7D%22%7D)',
        );

Update: i have removed location assert. And cy.wait now works!

        cy.location('pathname').should(
            'eq',
            '/clients(filter:%F0%9F%94%96/%7B%22-735573861%22:%22%7B%5C%22pageNumber%5C%22:1,%5C%22pageSize%5C%22:10%7D%22%7D)',
            {matchCase: false},
        );

That style also causes a problem

        expect(window.location.pathname).to.be(
            '/clients(filter:%F0%9F%94%96/%7B%22-735573861%22:%22%7B%5C%22pageNumber%5C%22:1,%5C%22pageSize%5C%22:10%7D%22%7D)',
        );

I didn't use location ()

@jianjiming Never mind, it brakes anyway(
Did not help

Was this page helpful?
0 / 5 - 0 ratings

Related issues

weskor picture weskor  ·  3Comments

carloscheddar picture carloscheddar  ·  3Comments

tahayk picture tahayk  ·  3Comments

szabyg picture szabyg  ·  3Comments

brian-mann picture brian-mann  ·  3Comments