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 serve 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:

.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:

Form error message

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

Testing exception behavior

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

Mocking HTTP/S request

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