Mocking HTTP/S Requests

When we need to ensure a decent user experience we do not only test the designed flow, but also exceptional cases. We have to check that the application responds to problems gracefully. Let’s say we have a feedback form. The typical scenario would be: user submits the filled out form and gets notified when it’s done. But what if a problem happens on the server side? The application is supposed to warn the user. How do we test such cases? We cannot reproduce the issue until everything is fine with the server side. However, we can use page.mockRequest to intercept submission request sent to the server and replace it with our own.

On demo page you can find a demo form. When user submits it the page emulates sending data:

fetch( … )
  .then(function( rsp ){
    rsp.status !== 200 && showAlert();
  .catch( showAlert );

If the response from the server has got status code different from 200 (OK) the form displays alert box:

In the example server always responds with status 200, unless it's down. If we want to simulate this particular case we need to replace the response from the server with our own. Overridden response will have status 500.

The test case for the exceptional behavior may look like that:

Here we make Puppetry listening to the next request containing “response.json” in the URL and replace it with errored one "500 Internal Server Error":

Then the test fills out the form and submits it. At the end we assert that user gets warned about the problem (ALERT_BOX is visible).

As you see, we can test exceptional behaviour. We can entirely emulate the server by mocking requests when it's not available. We can seed the client with predefined data when testing pages with dynamic content. And we can do much more.

Last updated