Effective testing ensures you have developed an application that runs smoothly and meets your users’ expectations. There are many methods you can use in order to test your app. However, mocking API stands out as the perfect method to test an application because it allows you to test your app without relying on live data.
You can mock an API through various paths. However, you should mock an API using app router because it is among the reliable ways to mock APIs. Still, many people struggle to do so because they don’t know the right way. Today, we are going to provide you with the best way to mock your API using an app router.
Why should you consider mocking an API using an app router?
If you are a developer, you might be aware of the fact that mocking API can help you to work more efficiently in a controlled zone with isolated components in order to get better testing results. You can improve these benefits by mocking an API using app router.
App routers can be excellent for you if you are mocking an API because they will help you to decrease delays by letting progress without the actual API. It helps your team to work on different components of an application simultaneously, leading to a faster development process.
Best way to mock an API using app router
When mocking an API through an app router, you must follow a few simple steps. However, you also need to do some basic coding. The best way you should follow to mock an API is mentioned below:
1. Initialize the project and install dependencies
To start the project and install dependencies, you have to go to your project directory. We have mentioned the steps you required to go to your directory:
-
Open your terminal or prompt a command
-
Once opening your terminal or prompting, you should navigate to the directory where you wish to develop your project.
After navigating the directory, you should develop a package.json by running the command
npm init -y
in order to activate the new Node.js project. It will develop a basic package.json file within the default setting.
To proceed, execute the command:
npm install express
It will install the Express npm package. However, you need to include this framework in your package.json as a dependency.
Lastly, you should develop a new file for your main server code and create another file named Mockdata.js for the mockdata you want to use.
2. Set up a mock data
Next, you must set up mock data by adding the following code in mockdata.js:
let products = [
{ id: 1, name: 'Product A', description: 'Description of Product A', ratings: '5', brand: 'Google' },
{ id: 2, name: 'Product B', description: 'Description of Product B', ratings: '4', brand: 'Apple' },
{ id: 3, name: 'Product C', description: 'Description of Product C', ratings: '2', brand: 'Microsoft' }
];
module.exports = {
products
};
3. Set up express server
Once setting up a mock data, you should set up an express server by adding the following code:
const express = require('express');
const { products } = require('./mockData'); // Import the products array
const app = express();
const port = 3000;
app.use(express.json());
Explanation
-
With this code, express is imported in order to create a web server.
-
The mockData module also provides the import of the product array.
-
An express application is developed and assigned to an app.
-
The server is ready to listen on port 300.
-
express.json() middleware is used to parse incoming JSON requests.
4. Define the route for CRUD operations
Once setting up your express servers, you should define the route for the CRUD operations. The following are the steps you need to follow to define these routes:
// Get all products
app.get('/api/products', (req, res) => {
res.json(products);
});
Explanation
// Get a product by ID
app.get('/api/products/:productId', (req, res) => {
const productId = req.params.productId;
const productFilter = products.filter(product => product.id == productId);
res.json(productFilter);
});
Explanation
// Delete a product by ID
app.delete('/api/products/:productId', (req, res) => {
products.map((item, index) => {
if (item.id == req.params.productId) {
products.splice(index, 1);
res.send(products);
} else {
res.send('not found');
}
});
});
Explanation
// Update a product by ID
app.put('/api/products/:productId', (req, res) => {
let productFound = false;
products.map((item, index) => {
if (item.id == req.params.productId) {
productFound = true;
Object.keys(req.body).map((key) => {
item[key] = req.body[key];
});
res.send(products);
}
});
productFound ? res.send(products) : res.send('Not Found');
});
Explanation
-
This route updates an existing product by its ID with the use of a PUT request.
-
It also checks whether the product is available. If found, it updates the product property with the data provided in the request body.
5. Start the server
Lastly, you should start the server with the help of the code mentioned below:
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Explanation
You should copy and paste the code mentioned below to complete the process:
const express = require('express');
const { products } = require('./mockData');
const app = express();
const port = 3000;
app.use(express.json());
// Get all value
app.get('/api/products', (req, res) => {
res.json(products);
});
// Get the value by using ID
app.get('/api/products/:productId', (req, res) => {
const productId = req.params.productId;
const productFilter = products.filter(products => products.id == productId);
res.json(productFilter);
});
// Insert the value
app.post('/api/products', (req, res) => {
products.push(req.body)
res.send(products);
});
// Delete the value by using ID
app.delete('/api/products/:productId', (req, res) => {
products.map((item, index)=>{
if(item.id == req.params.productId) {
products.splice(index, 1);
res.send(products);
} else {
res.send('not found');
}
})
});
// Update the value by using ID and pass data in JSON format
app.put('/api/products/:productId', (req, res) => {
let productFound = false;
products.map((item, index)=>{
if(item.id == req.params.productId) {
productFound = true
Object.keys(req.body).map((key)=>{
item[key] = req.body[key]
})
res.send(products);
}
})
productFound ? res.send(products) : res.send('Not Found');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Conclusion
In order to test a product or app, you should definitely mock an API using app router. This is among the best paths to mock an API for testing. However, you should perform the right steps to mock an API using this. We have tried to guide you in order to mock an API through the best and easiest steps in this article. We hope that this guide will be helpful for you in mocking your API. You can also contact faux api because our experts will develop a mock API for you.
FAQ
1. Can we create an API using node/express?
Yes, you can use Node.js and Express.js to create an API. Express.js is among the famous frameworks to develop an API on top of Node.js.
2. Is express node good for creating a mock API?
Yes, express is a popular option for developing mock APIs because of its flexibility and ease of use.
3. Why should you use faux API instead of Node express to mock an API?
While building a mock API through Node or Express, you should go through a hectic step mentioned in this article. Instead, you should consider working with Faux API because we will deliver your Mock API more effectively. It means you will get your API without any effort and easy-to-use. Start mocking your API today.