Introduction Of Node js
Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to execute JavaScript code server-side. It is built on the V8 JavaScript runtime engine, which is the same engine that powers the Google Chrome browser. Node.js enables the use of JavaScript for both client-side and server-side development, providing a unified language throughout the entire web application stack.
Key Features
- Non-blocking I/O
- Single-threaded, event-driven architecture
- JavaScript on the server-side
Why Node.js
High performance
Scalability
Large and active community
Setting Up Node.js
Installing Node.js and npm
node app.js
Basic commands (node -v, npm -v)
Creating and running a Node.js script
Node app.js(app.js is file)
What is npm?
which stands for “Node Package Manager,” is the default package manager for Node.js. It is a command-line tool and an online repository of software packages or modules for Node.js. npm makes it easy for developers to share and reuse code, manage project dependencies, and streamline the process of integrating third-party libraries into their applications.
What is an API ?
Here are below some most common challenges and solutions faced by the Developer while creating an API
Introduction
An API is a simple concept which helps and allows two computer programs to communicate, it’s a medium between two apps, which coordinates the sharing of data and services. APIs or Application Programming Interfaces are quickly getting famous and renowned day by day. They are a good medium for connecting different types of applications, collecting and sharing information and data and ideally working together. These are turning out to be very important for our modern software development.
As creating API is in boom developers are also facing some pros and cons related to the same. Below we will be discussing about some challenges :-
Security Challenges
In 2023 around 90% organisations faced security issues and almost 15 โ 20 % had an API security infringement, APIs are available to security threats, and if the API are locally available on the internet this issue will only increase aggressively.
Security concerns include โ Sanitize and bifurcate the upcoming data. This helps and protects against attacks like SQL injection, XSS, etc.
Documentation Challenges :-
Unstable or deficient documentation makes a huge difference on the use of APIs, as if this happens it gives a bad result and experience So its really mandatory or more important to ensure a good developer experience for a successful API creation.
Here is how one can tackle the documentation related challenges
Complete. Clear and detailed data should be provided for a perfect and accurate documentation. It should include examples, related codes etc.
Expandability and Performance
As per the recent survey most users want API to respond within a few seconds and also consider the API performance an important aspect. An API handles an increased number of requests, without degrading the performance.
Here are ways to ways to address expandability and performance
Distribute incoming requests to different multiple servers using the kind of load balancers available, as they help and assure the single server doesnโt become a setback for the data which can hamper the overall performance. This idea or method improves the availability and authenticity.
Adaptation and Backward Compatibility
APIs make progress over time. In this manner changes are constant and unpreventable. In time what happens while updating an API can break the existing integration, this leads to interference or disturbance to clients who rely or are dependent on the previous versions.
Hence if we maintain the backward compatibility while introducing the new update or a feature, we can save the data and balance everything in a proper manner.
Tips to Avoid adaptation and backward compatibility
Implementing versioning strategies can help in the changes erupting and keeping existing clients.
Make a note and clear deprecation policy with users in advance to avoid future hassle and exception to old versions.
Integration Challenges
As we all know API interacts with many external systems, data, and services. Every system, services has their own rules and protocols to deal with.
This makes the integration challenge a common phenomenon.
This entangles the communication with the huge system, and overcomes the main purpose of API.
A developer should adopt protocols like REST or GraphQL for the good consistency certainty.
Up to date API documentation should be used which includes examples, error handling guidelines.
Writing Unit Test in Node.js
In Node.js writing unit tests typically require using a testing framework, which can be Mocha, Chai, or Jest and assemble the tests to check the individual units of code.
Writing a Unit Test in Node.js is not only simple but also effective, mainly when we use a framework like Jest. We can also write tests for synchronous and asynchronous code. Mock functions and also should check the variety of conditions using Jestโs rich set of matchers.
With these basics, you can start writing unit tests and go ahead with the further work.
Jest is a most renowned and easy to use testing library. Here will be a basic guide for writing the unit test in Node.js Focusing on Jest :-
Steps for wring Unit Test in Node.js
- Install Jest
- Firstly, you need to install Jest in your Node.js project. If you have initiated npm init, run that command first if not first we need to initiate and run the command.
- Then install Jest โ After installingโฆ.
- Add the Test Script
- As the Jest is installed, you should add the test script to package.json file to run the tests for proper working.
- Create a Function to Test
- Simply we need to add a function to test like example sum.js.
- Write a Unit Test
- Create the file in the _tests_ folder or any other test folder, and name the file like sum,test,js
- Run The Test
- Now execute with running the test. This will perform the Jest, which will search for files with the .test.js suffix and continue the test inside them. At the end this will show the results in your terminal.
These are the following steps to write unit tests for APIs with both GET and POST methods in Node.js, you can Jest and Super test
Supertest is a library for testing HTTPS APIs. This combines with Jest and allows you to test your express or other Node.js API.
Below are a few points for writing unit tests for 10m APIs, mentioning both GET and POST.
Install Must Have dependencies
- Firstly we have to ensure that we have Jest, Supertest and Express in our system. If not we need to install it first with npm.
Create your Express API
- We will be needing API with both GET and POST routes
Write Unit Test for the APIs
- Create a Test folder in your project root, then create the test file for the API Test
Test Multiple APIs
- Here you can enlarge the 10 more API routes, assuming we are testing both GET and POST for different resources eg, product, user, order and others.
Running Test
- Now we can run the test with Jest
Conclusion
Super test allows you to make HTTPs in the Express App and state the response.
Jest takes care of the declaration and the Test runner.
In this method each GET and POST can have many conditions like sometimes failure, success, missing parameters etc.
One can also add more GET and POST routes in app.js and mention the correlated tests.
By following the above structures, one can also write 10 or more API routes in Node.js with the help of Jest and Supertest. This makes sure that your API works and behaves as per your requirements.
Example:-
For the purpose of this example, let’s assume you have an Express app with 10 endpoints, both GET and POST methods. Here is an example API with both GET and POST routes.
javascript
// app.js (your Express app)
const express = require(‘express’);
const app = express();
app.use(express.json()); // Middleware to parse JSON request bodies
// Example GET and POST routes
app.get(‘/api/user/:id’, (req, res) => {
const { id } = req.params;
res.status(200).json({ id, name: `User ${id}` });
});
app.post(‘/api/user’, (req, res) => {
const { name, age } = req.body;
if (!name || !age) {
return res.status(400).json({ error: ‘Name and age are required’ });
}
res.status(201).json({ id: 1, name, age });
});
// More routes (up to 10 APIs)
module.exports = app;
Create a __tests__ folder (or any test folder you prefer) in your project root, and then create a test file for your API tests, e.g., api.test.js.
// __tests__/api.test.js
const request = require(‘supertest’);
const app = require(‘../app’); // Import the Express app
describe(‘API Endpoints’, () => {
// Test GET request for /api/user/:id
test(‘GET /api/user/:id – success’, async () => {
const response = await request(app).get(‘/api/user/1’);
expect(response.status).toBe(200);
expect(response.body).toEqual({ id: ‘1’, name: ‘User 1’ });
});
// Test GET request for /api/user/:id (non-existent ID)
test(‘GET /api/user/:id – not found’, async () => {
const response = await request(app).get(‘/api/user/999’);
expect(response.status).toBe(404); // Assuming no handler for non-existent users
});
// Test POST request for /api/user (success case)
test(‘POST /api/user – success’, async () => {
const newUser = { name: ‘John Doe’, age: 25 };
const response = await request(app).post(‘/api/user’).send(newUser);
expect(response.status).toBe(201);
expect(response.body).toEqual({ id: 1, name: ‘John Doe’, age: 25 });
});
// Test POST request for /api/user (missing fields)
test(‘POST /api/user – missing fields’, async () => {
const newUser = { name: ‘John Doe’ }; // Missing age
const response = await request(app).post(‘/api/user’).send(newUser);
expect(response.status).toBe(400);
expect(response.body.error).toBe(‘Name and age are required’);
});
// More tests for additional APIs (up to 10)
test(‘GET /api/user/:id (user 2)’, async () => {
const response = await request(app).get(‘/api/user/2’);
expect(response.status).toBe(200);
expect(response.body).toEqual({ id: ‘2’, name: ‘User 2’ });
});
test(‘POST /api/user – user 2’, async () => {
const newUser = { name: ‘Jane Doe’, age: 30 };
const response = await request(app).post(‘/api/user’).send(newUser);
expect(response.status).toBe(201);
expect(response.body).toEqual({ id: 1, name: ‘Jane Doe’, age: 30 });
});
// You can keep adding more tests for other routes
});
Related Blogs