How to mock your frontend application environment in about a minute!
Tags: webdev, testing, javascript
Published: 2020-05-07 13:51:29

---
title: How to mock your frontend application environment in about a minute!
published: true
description: Discover a way to fully mock a navigation scenario just by going over it one time and sharing/reusing it independently.
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/1e15rs6chpc6l1p6v22p.jpg
tags: #webdev, #testing, #javascript 
---

_If you want to freshen up on what modern application architectures have brought to the table, what that entails for frontend development and testing and why we propose mocking as a viable solution, you can go ahead and check out the prelude to this article:_ 
{% link https://dev.to/igneel64/juggling-the-multi-service-dependent-frontend-15k1 %}

### The goal 🎖
Our target is to develop, test and validate our assumptions faster and with more confidence using API mocking for frontend environments. Regardless if you require simply a "quick" way to mock an environment, or a more sophisticated approach to adopt inside your team independent of size and complexity. Hope I can spark some thoughts for experimenting with a new mindset.

### The problem and one common misconception 💊
One common misconception when engineers hear API mocking is that they explicitly wait for specifications, contracts and detailed documentation to be able to have something to work with. 
__This _de-facto_ expectation is a conceptual blocker to reaping the serious benefits that API mocking can bring you.__

Depending on the size of your team and the maturity of the application you are working on, some quick questions dumpen the mood even further around our efforts:
- Do we have a proper API documentation ?
- Is the documentation up-to-date and why not ?
- Do we have the time/resources to create and maintain API documentation ? 

Taking into account the fact that modern frontend applications can depend on multiple APIs handled by different teams or even domains, we can consider the best case scenario:
> With solid team responsibilities, diligence and effort, in medium and large teams you will probably find the assets in some form of [Swagger](https://swagger.io/) definitions or [Postman](https://www.postman.com/) collections that you can read and even mock with some tooling!

If you are already there, that is a great start but in the case you are working on larger scale projects, more questions start creeping up from the back of your head 🐍
- Does every team document their API in the same tool/repository ?
- How many third-party APIs our application is pulling data from and do they have a proper documentation ?

_Before this sounds too depressing..._

#### For a large span of use cases, you do not require all of these criteria to mock your API environment 🙅‍♂️

<hr/>

### The issue and the 1-minute solution

So imagine the only thing that you have access to is a page or a set of pages, you have to work on in your own development environment. The API interactions that you aim to mock are there, happening in production, staging, test or any environment that you want to mock them from. 

What you want is to be able to record and replay responses independently of the presence of the actual system. To add into it, you don't want only a specific endpoint, but all the endpoints from not one but more than one hosts.

#### Here comes

_All the code that you need for this technique can be found in this [sandbox](https://codesandbox.io/s/puppeteer-snapstub-sfrey?file=/README.md) with brief instructions._

What if there was a way to just specify some URL criteria for the endpoints you would like to mock, navigate to the set of pages that have these interactions and store them automatically so that you can use it later with a mock server ?

__Seems there is a way you can do it; independent of backend/frontend implementation and without complex logic or many dependencies.__
The technique involves the [snapstub](https://github.com/ruyadorno/snapstub) CLI tool and the [Puppeteer](https://github.com/puppeteer/puppeteer) library.
_It does not have a name yet but we can call it `puppeteer-snapstub`._

![puppeteer snapstub](https://dev-to-uploads.s3.amazonaws.com/i/fpxkni4wfvns2d7suzw1.png)

The features that we are interested in from __Puppeteer__ involve the capability to open a browser and [intercept network requests](https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-pagesetrequestinterceptionvalue) with certain filter criteria.
```javascript
    patterns: [
      {
        urlPattern: "*host-you-want-to-intercept.com*",
        resourceType: "XHR",
        interceptionStage: "HeadersReceived"
      }
      /*
        Add as many patterns as you like
      */
    ]
```
From __snapstub__ we are intereted in its exposed [programmatic API](https://github.com/ruyadorno/snapstub#programmatic-api) that allows us to add new mock entries and certainly the server that can then replay them.
```javascript
snapstub.save({ url, stdin, saveOptions: { ... });
```

__The process goes just like:__
1. You open up a page with Puppeteer.
2. You do the interactions that will trigger the requests you expect.
3. Close down puppeteer and start the snapstub server.
4. Mocks are ready and waiting.

This is it, you now have mock responses for any network request that satisfied the criteria that were specified. When you want to use these endpoints during development just change the hosts to request those APIs from to use `localhost:8059` and you are good to go.

![The process](https://dev-to-uploads.s3.amazonaws.com/i/662h98hbva72wziefzsf.png)

In less than a minute, _the time that it will take you to navigate between the pages_, you have a folder with all the mock requests recorded and ready to be automatically replayed. 
It is now portable, ready to be shared with the team or even stored in the frontend repository and most of all 100% available.

#### Special thanks
This article and methodology would not be without stumbling upon a presentation by [Ruy Adorno](https://dev.to/ruyadorno) with the topic of _Mocking APIs for fun & profit_ in an [npm newsletter](https://www.npmjs.com/npm-weekly) some time ago.

_Drawings made in the amazing [excalidraw](https://excalidraw.com/)_
_Image by <a href="https://pixabay.com/users/ArtisticOperations-4161274/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4578480">F. Muhammad</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4578480">Pixabay</a>_