This is the last post in our series on mocking data for testing purposes. So far, we have seen how to generate mock data using Mockaroo and then how to incorporate such fake data in our Angular application.
Today, let’s push this one step further and use that same JSON data to mock our entire backend server, including CRUD (CReate Update Delete) operations, so you can also test data updates.
Enter JSON Server
JSON server is a small npm library that reads a JSON file and turns it automatically into a RESTful web server. Yes, you read that right: All we need as input is our JSON data in a file!
The format of that JSON is one single object where each property will be turned into a backend endpoint. So, for instance, say you need to support two types of data: users and teams.
Then your JSON database will look like this:
{
"users": [
// Array of all users data
],
"teams": [
// Array of all teams data
]
}
Code language: JSON / JSON with Comments (json)
You would substitute those arrays with the mock data generated with Mockaroo, and then running JSON server would give you the following RESTful API:
HTTP GET /users
=> Returns the list of all usersHTTP GET /users/21
=> Returns the user withid = 21
HTTP POST /user
=> Creates a new userHTTP DELETE /user/21
=> Deletes the user withid = 21
HTTP PUT /user/21
=> Updates the user withid = 21
JSON server also supports pagination, full-text search, and custom routes if you want to add more endpoints to your test backend. Any changes you make to your data persist in your JSON file, too. This means you have a single file database for testing purposes, which is excellent!
If you want to try it, here is a complete tutorial on how to use JSON server with Angular apps. The getting started section of the npm package is also very well documented.