Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why stub in cypress may not work for route called after page was loaded

Tags:

cypress

I am using cypress to write tests and have a problem which doesn't appear in every test. In some cases it works and I don't know why. So...

The Problem:

I defined a route and alias for it in beforeEach:

beforeEach(function () {
  cy.server()
  cy.route('GET', '/favourites?funcName=columnPreset', []).as('columnPresetEmpty')
  cy.visit('#/search')
})

Stub works fine if http request occured on page load. But if I perform request responding to click event (modal dialog opens and executes http request) it just appear in commands not makred as stubbed and following cy.wait('@columnPresetEmpty') fails with request timeout.

 it('does not work', function () {
   cy.get('[data-test=button-gridSettings]').click()
   cy.wait('@columnPresetEmpty')
 })

At the same time in other tests I have almost similar functionality where request is performed just by clicking on a button, without opening new modal window. It's the only difference.

What am I doing wrong?

like image 934
soeik Avatar asked Dec 29 '25 19:12

soeik


2 Answers

The issue might be cypress can not yet fully handle fetch calls. You can disable it the following way but make sure you have fetch polyfill. This will then issue XHR requests which cypress can observe.

cy.visit('#/search', {
    onBeforeLoad: (win) => {
        win.fetch = null
    }
})

More to read here: https://github.com/cypress-io/cypress/issues/95#issuecomment-281273126

like image 159
gabberr Avatar answered Jan 01 '26 22:01

gabberr


I found the reason causing such behavior. Problem was not in a modal window itself, but code performing second request was called in promise's callback of another request. Something like:

fetch('/initData')
  .then(loadView)

And loadView function executed second fetch.

So when I removed loadView from promise's callback both requests become visible for cypress.

like image 22
soeik Avatar answered Jan 01 '26 20:01

soeik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!