
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
To test a product or application effectively, using a mock API with an app router is a practical approach. It allows you to simulate real API behavior and validate your application without relying on a live backend.
In this article, we have outlined simple and effective steps to help you create and use mock APIs with ease. By following this guide, you can improve testing, identify issues early, and streamline your development process.
If you prefer a faster solution, you can use the Faux Instant API to instantly create mock APIs without signup, or use Faux production API to set up APIs for your project with ease after signingup.
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?
Building a mock API using Node or Express often involves multiple setup steps. Instead, you can use the
Faux Instant API to create mock APIs instantly without signup. It provides a simple and efficient way to generate APIs without complex configuration. You can get started quickly and focus on development without additional effort. Start mocking your API today.