Build A Real-Time Chat Application With Socket - Io and Node - Js (With Automated Testing)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.

js [With Automated Testing] - DEV Community

Pavan Belagatti
Posted on Apr 16

58 4 6 6 10
Build a Real-time Chat Application with Socket.io
and Node.js [With Automated Testing]
#node #devops #beginners #tutorial
In this tutorial, let's learn how to use Socket.IO and Node.js and create a simple chat
application. We will set up a basic Node.js app and install the necessary dependencies.
With a basic chat interface and add a simple feature where users can easily send and
receive messages with the help of the Socket.IO connection. Socket.io is a widely used
library that helps with real-time communication between web clients and servers. Finally,
we will write a simple test with the Mocha framework and automate it through Harness CI.
Prerequisites
Node.js installed
Npm installed
Free Harness CI account to automate testing
Tutorial
https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 1/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Install Node.js on your machine: You can download and install the latest version of
Node.js from the official website: https://nodejs.org/
Create a new Node.js project: Open a terminal window and create a new directory for
your project. Navigate into the new directory and run the following command to create
a new package.json file for your project:
npm init -y

Install Socket.io: Run the following command to install Socket.io in your project:
npm install socket.io

Create a new Node.js server: Create a new file named server.js in your project
directory and add the following code:
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

app.use(express.static(__dirname + '/public'));

io.on('connection', (socket) => {


console.log('A user connected');

socket.on('disconnect', () => {
console.log('A user disconnected');
});

socket.on('message', (message) => {


console.log('Received message:', message);
io.emit('message', message);
});
});

http.listen(3001, () => {
console.log('Server started on port 3001');
});

This code adds an event listener for the message event, which is emitted by the client
when the user clicks the send button. The server logs the message to the console and
https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 2/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

then emits a message event to all connected clients using the io.emit() method.
Create a new HTML file: Create a new file named in the public directory index.html
and add the following code. It adds an input field and a button to the index.html file to
allow users to send messages to the server. Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>Socket.io Tutorial</title>
</head>
<body>
<h1>Socket.io Tutorial</h1>
<div id="messages"></div>
<input id="message-input" type="text" placeholder="Type your message here">
<button id="send-button">Send</button>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
socket.on('connect', () => {
console.log('Connected to server');
});
socket.on('disconnect', () => {
console.log('Disconnected from server');
});
const messages = document.getElementById('messages');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
sendButton.addEventListener('click', () => {
const message = messageInput.value;
socket.emit('message', message);
messageInput.value = '';
});
socket.on('message', (message) => {
const messageElement = document.createElement('div');
messageElement.innerText = message;
messages.appendChild(messageElement);
});
</script>
</body>
</html>

Start the server: Run the following command in your terminal to start the server:
https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 3/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

node server.js

You should see the output on your terminal below,


Server started on port 3001

And when you open the 3001 on your local, you should see your chat app running.

This should be your application folder structure as of now.


socketio-nodejs-tutorial/
|- node_modules/
|- public/
| |- index.html
|- server.js
|- package.json

Add a Test Case to the Chat Application


Since Socket.io is a real-time framework, it can be a bit challenging to write automated
tests for it. However, we can write a simple test to verify that the client and server can
communicate with each other and send/receive messages.
Install the mocha testing framework and the chai assertion library by running the
following command:
npm install mocha chai --save-dev

[Note: Run the above command in the root of your app]


https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 4/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Make a new folder named test and add a file named test.js in it with the following
code.
const assert = require('chai').assert;
const io = require('socket.io-client');
const serverUrl = 'http://localhost:3000';

describe('Socket.io test', function() {


let client1, client2;

before(function(done) {
// Connect to the server
client1 = io.connect(serverUrl);
client2 = io.connect(serverUrl);
done();
});

after(function(done) {
// Disconnect from the server
client1.disconnect();
client2.disconnect();
done();
});

it('Should be able to send and receive messages', function(done) {


client1.emit('message', 'Hello, world!');
client2.on('message', function(msg) {
assert.equal(msg, 'Hello, world!');
done();
});
});
});

Now make sure your app is running.


In another terminal open the application and run the following command to test the
application.
npm test

You should see a successful test passing message.


https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 5/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Push your application code to a source control management system such as GitHub.
My application code is here - chat-app-tutorial
You can fork it or use your own (the one you pushed to your GitHub) to setup automated
tests using a CI tool. We are going to extend this tutorial to show you how you can
automate tests.
Automate Tests using a CI tool
Here, we will be using the fastest CI tool, Harness.
Sign in to your free Harness CI module.
Get started with creating your first pipeline

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 6/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Authenticate with your GitHub account as your application code is present there.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 7/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Select your application repository.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 8/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Next, start configuring the pipeline.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 9/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Select Node.js from the list as our application is written in Node.js. What you will then see
is a default yaml configuration for your Node.js application.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 10/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Continue and click the 'Create the pipeline' button. You will the pipeline dashboard.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 11/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Click on the 'Build Node App' stage, you should see the run step added by default with
pre-configurations.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 12/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Click the 'Build Node App' step, that is under execution and you will see the default
configurations.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 13/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

We want the application to be running before testing it. How to make the application run?
We will add a background step to run the server.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 14/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Configure the Background step with the commands shown below.


npm install
npm install express --save-dev
node server.js

The screenshot of the same step is shown below

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 15/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Apply changes and add another step to test the application.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 16/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Choose the Run step from the step library.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 17/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Add the following commands to the run step.


npm install
npm test

You can see the screenshot of the run step with commands added.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 18/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Apply changes and save the pipeline.


At this point, this is how your pipeline should look like.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 19/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Save everything and run the pipeline.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 20/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

You should see a successful pipeline execution with test passing.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 21/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

You have the pull and push triggers already enabled by default.

So when any developer pushes code to your main branch, the pipeline gets triggered and
runs the test. This way the tests can be automated easily.
If you like to learn CI/CD from scratch, I have another tutorial you might like. Take a look.

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 22/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Learn How to Setup a CI/CD Pipeline from


Scratch
Pavan Belagatti ・ Mar 1 ・ 8 min read
#tutorial #devops #go #kubernetes

Top comments (4)


Pedro Pimienta M. • Apr 19
Great post, I'm going to read better when I reach the section to the course of Node that I
doing rigth now.

attilalb • Apr 19
Nice tutorial, easy to follow 😄

Tochukwu Adams • Apr 18


Great piece!

Pavan Belagatti • Apr 18


Thanks:)
Code of Conduct • Report abuse

DEV Community
An Animated Guide to Node.js Event Loop

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 23/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

Node.js doesn’t stop from running other operations because of Libuv, a C++ library
responsible for the event loop and asynchronously handling tasks such as network
requests, DNS resolution, file system operations, data encryption, etc.
What happens under the hood when Node.js works on tasks such as database
queries? We will explore it by following this piece of code step by step.

Pavan Belagatti
Developer & DevOps Advocate!
JOINED
Apr 22, 2018

More from Pavan Belagatti


Kubernetes GitOps: A Beginner's Guide with a Hands-On Tutorial
#gitops #tutorial #kubernetes #git

3 Ways to Optimize Your Node.js Application Performance


https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 24/25
4/21/23, 2:31 PM Build a Real-time Chat Application with Socket.io and Node.js [With Automated Testing] - DEV Community

#javascript #node #tutorial #productivity

Learn How to Use Artifactory as a Docker Registry


#devops #tutorial #productivity #cloud

DEV Community

15 ChatGPT Plugins to hack productivity


✨ TweetGPT
✨ Promptheus
✨ YouTube Summary
✨ Merlin
✨ Share GPT
✨ WebChatGPT
✨ ChatGPT Writer
✨ Superpower ChatGPT
✨ ChatOnAi
✨ ChatGPT Prompt Genius
✨ Open AI ChatGPT for Gmail
...
Read full post

https://dev.to/pavanbelagatti/build-a-real-time-chat-application-with-socketio-and-nodejs-with-automated-testing-38h8 25/25

You might also like