DEV Community

Manuele J Sarfatti
Manuele J Sarfatti

Posted on

How to Test Your Fetch API Requests with Cypress

Cypress is awesome. With Cypress you can do everything, including simulating your back end by stubbing requests, or getting freshly brewed coffee to your bed as you wake up every morning 1.

Unfortunately, Cypress does not currently support intercepting requests made with the more modern Fetch API, but only with the not-so-good old XMLHttpRequest.

From their own docs:

Please be aware that Cypress only currently supports intercepting XMLHttpRequests. Requests using the Fetch API and other types of network requests like page loads and <script> tags will not be intercepted or visible in the Command Log. See #95 for more details and temporary workarounds.

Luckily there is a very simple yet very effective workaround: include a fetch polyfill, then delete window.fetch to make sure the browser falls back to XMLHttpRequest.

Here is the easy 3-step process:

  1. Install the fetch polyfill package in your project, if you haven't already

    $ npm install whatwg-fetch --save
    ~or~  
    $ yarn add whatwg-fetch
    
  2. Import it in your project (you'll probably do it in your index.js file)

    /* file: src/index.js */
    
    import 'whatwg-fetch';
    
  3. Instruct Cypress to delete window.fetch before every window load

    /* file: cypress/support/index.js */
    
    // Delete window.fetch on every window load
    Cypress.on('window:before:load', win => {
      delete win.fetch;
    });
    

That's all, happy stubbing 🚀


NOTES

1 - Not yet confirmed

Top comments (1)

Collapse
 
shivasrini profile image
Shiva Srinivasan

How would you delete the fetch call when there is no visit happening but the fetch call is either a webhook or an event. For example we have a form page where new users type in their email. Once the email is typed in and the user has clicked on the next field in the form a fetch call is made to check if the email is already in use. How do I mock that? I cannot do cy.visit. What is the alternative?