A simple Node.js REST server simulator for Testing

A simple Node.js REST server simulator for Testing

Problem

You are developing a client application (AngularJS) and need to retrieve data from a REST API service. However, you often lack access to the remote service, or it doesn’t have the required data for your tests (e.g., dynamically generated data).

<img class="aligncenter" src="/assets/img/uploads/2016/10/nodeminiproblem_1.png?resize=600%2C173" align="middle" data-recalc-dims="1" />

A direct request to a test .json file is not possible due to browser security restrictions—browsers cannot directly access the file system.

---

Solution – Concept

A client application can send a GET request to a local server, which then serves a JSON file as a response.

This local server can be implemented in Node.js, which handles HTTP requests and serves static files.

---

Solution – Implementation

The code and installation guide are available here: 🔗 GitHub Repository

Project Structure

The project follows a simple structure:

<img class="aligncenter" src="/assets/img/uploads/2016/10/nodeminiserverstructure_1.png?resize=300%2C191" align="middle" data-recalc-dims="1" />

Example Response

Here’s an example of a JSON response:

<img class="aligncenter" src="/assets/img/uploads/2016/10/nodeminiserverresponse_1.png?resize=600%2C210" align="middle" data-recalc-dims="1" />

---

Solution – Details

The server.js file creates an HTTP server that listens for requests. It uses a loaderModule, which contains a class responsible for retrieving the JSON data.

server.js