Instructor: Inside of our application, we're going to do async componentDidMount, const data equals await fetch, the Star Wars API URL. Then we'll unwrap that promise, and set our Star Wars property to our data. We'll add that to our state object.
Then inside of our HTML, let's add an h3 with a data property of Star Wars. Then we'll do this.state.StarWars.url, receive Star Wars data, if not, then something went wrong. Puppeteer gives us the ability to intercept requests made on a page.
Not only can we write tasks that check the content of our h3 with successful requests, but we can intercept the request and force the failure. This way, we can test our UI on both successful requests and unsuccessful ones.
Inside of our tests, we going to add a page.setRequestInterception to true. We'll do page.onRequest, intercept the request with an if check on that request to make sure the URL includes swampy. Then we're going to abort this request. If not, then we'll continue it on.
This setRequestInterception is basically a flag that enables us to access each request made by the page. Once a request is intercepted, the request can be aborted with a particular error code. We could cause a failure, or we can intercept, then continue after checking some conditional logic.
Now, let's go ahead and run a test checks this h3 content. We'll do test, fails to fetch Star Wars endpoint. We'll do const h3 equals await page.eval, our data attribute, Star Wars. We'll grab the inner HTML out of it, and then expect h3 to be receive Star Wars data.
As we can see in our running app, as soon as the page loads, it goes out and fetches the Star Wars API. When it receives the data, our h3 text changes to received Star Wars data. Let's throw a .only on this test, and we're only testing this one, then save it, and run our npm test.
That test is failing. It looks like it's getting the something went wrong text, instead of our received Star Wars data that we put to test. This goes to show that our request interception logic that we wrote is working as intended.
On each request, we filter out the one that includes the swampy string and abort it. Everything else, we let continue on. Our failed request text should actually be, "Something went wrong." Now, let's remove this only, and skip our console and exceptions tests, because they will fail with the failed fetch request.
Run our test in debug mode this time, so we can actually see the h3. If we notice, that something went wrong text stays the same the whole time. All of our tests pass, which means that we successfully aborted the Star Wars request.
It's also worth noting that, when intercepting requests, we can control what headers are sent, what error codes are returned, and return custom body responses.