How to Test Your Fetch API Requests with Cypress
Manuele J Sarfatti
Posted on September 19, 2019
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:
-
Install the
fetch
polyfill package in your project, if you haven't already
$ npm install whatwg-fetch --save ~or~ $ yarn add whatwg-fetch
-
Import it in your project (you'll probably do it in your
index.js
file)
/* file: src/index.js */ import 'whatwg-fetch';
-
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 🚀
Posted on September 19, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024