Socket.on not being called in mocha - javascript

I try to test socket.io using mocha, but i have a problem when make a socket call on. I think socket is not connected, because the console log not triggered but the console.log outside the socket call is show. Or it's wrong about how i use the done() method ?
const { assert } = require('chai');
const ioServer = require('socket.io');
const ioClient = require('socket.io-client');
const http = require('http');
const socketUrl = 'http://localhost:5000';
const options = {
transports: ['websocket'],
'force new connection': true,
};
let server;
let client;
let httpServer;
describe('Socket', () => {
beforeEach(done => {
httpServer = http.createServer().listen();
server = ioServer(httpServer);
client = ioClient.connect(socketUrl, options);
server.on('connection', socket => {
console.log('connected server');
socket.emit('echo', 'Hello World');
});
client.on('echo', message => {
console.log('connected client');
console.log(message);
});
console.log('test');
done();
});
afterEach(done => {
server.close();
client.close();
done();
});
it('It should connect socket', done => {
client.on('echo', message => {
assert.equal(message, 'Hello World');
});
done();
});
});
Here's the screenshoot cli terminal when running mocha.
Mocha

Related

Unable to stub asynchronous method inside Express server module with Chai-http and sinon js

I am trying to stub asynchronous methods using sinon js when using with chai-http
Please find the code below
index.js
const { getConfig, getConn } = require('./service/service');
const express = require('express');
const app = express();
let getConfPromise = getConfig();
let getConnPromise = getConfPromise.then(conf => getConn(conf));
Promise.all([getConfPromise, getConnPromise])
.then(([config, conn]) => {
console.log('config: ', config);
console.log('conn: ', conn);
app.get('/test', (req, res) => {
res.send(conn);
});
const port = 3000;
app.listen(3000, () => console.log(`Listening on port ${port}...`));
}).catch(err => {
console.error("Things did not go well: ", err)
})
module.exports = app;
service.js
const getConfig = () => {
return new Promise((resolve, reject) => {
resolve({
server: {
port: 8080
},
status: "from service"
})
})
}
const getConn = (conf) => {
return new Promise((resolve, reject) => {
try {
console.log('conf: ', conf);
let confLocal = JSON.parse(JSON.stringify(conf));
confLocal.connStatus = 'Connection is up';
resolve(confLocal)
} catch (error) {
console.log("Did not get value: ",error);
}
})
}
module.exports = {
getConfig,
getConn
}
Please find the test code below
let mocha = require('mocha');
let sinon = require('sinon')
let chai = require('chai');
let chaiHttp = require('chai-http');
let service = require('../src/service/service');
let app = require('../src/index');
const { after } = require('mocha');
chai.use(chaiHttp);
describe('Index test', () => {
it('test1', (done) => {
sinon.stub(service, 'getConfig')
.resolves({
server: {
port: 7777
},
status: "from test"
})
sinon.stub(service, 'getConn')
.resolves({
server: {
port: 7777
},
status: "from test",
connStatus: 'Connection is up from test'
})
chai.request(app)
.get('/test')
.end((err, res) => {
console.log('Chai HTTP err: ', err);
if (err) done(err);
chai.assert.equal(res.status, 200, 'Response status is incorrect')
console.log('Test case: ',res.body);
done();
});
})
})
When running the test cases, I am not getting the stubbed response, but I am getting the actual object from the service.js.
How to correctly stub? Please help.
Thanks in advance

Cannot connect to Redis using node js module

I have redis up and running on port 6379, connecting via telnet works fine.
I'm trying to connect to it on node.js, but i'm getting no response from the event listeners.
If i make a call any function like client.set() I get: "ClientClosedError: The client is closed".
This is the code im running:
const redis = require('redis');
const client = redis.createClient(6379);
client.on('connect', () => {
console.log('connected');
});
client.on('end', () => {
console.log('disconnected');
});
client.on('reconnecting', () => {
console.log('reconnecting');
});
client.on('error', (err) => {
console.log('error', { err });
});
setTimeout(() => {console.log("goodbye") }, 20*1000 );
Nothing happens for 20 seconds, and then it closes
Starting from v4 of node-redis library, you need to call client.connect() after initializing a client. See this migration guide.
const redis = require('redis');
const client = redis.createClient({ socket: { port: 6379 } });
client.connect();
client.on('connect', () => {
console.log('connected');
});
You might also want to consider running the client connect method with await in an asynchronous function. So you don't have to worry about event listeners.
const redis = require('redis');
(async () => {
try {
const client = redis.createClient({ socket: { port: 6379 } });
await client.connect();
console.log('connected');
} catch (err) {
console.error(err)
}
})()

How to debug Node + Socket.io CPU Issues, doing nothing but connections 100% cpu

I'm running a Node Socket.io server with Express with docker compose
and client side is vue.js. The service is running well, but the CPU grows 100
and stays, i'm every time doing restart to my docker compose,still after 5 minutes cpu reaches jumping 100%.. I don't know what to check since there's laterally nothing but the most basic stuff..client and server connection and disconnect works perfect,all events is working good but i don't know which way i ll focus to find my bugs.
Here are my backend code socket code.
import { verifyToken } from './middleware/auth';
import Socket from './components/services/socket';
const app = express();
const socketPort = process.env.SOCKET_PORT || 8001;
const io = require('socket.io')(socketPort);
const port = process.env.PORT || 3000;
app.listen(port, () => {
log.info(`HTTP server is running 🚀 on port ${port}
Socket service running 🚀 on port ${socketPort}
Process Pid: ${process.pid}`);
});
const socket = new Socket(io);
socket.modelLoaded();
socket.js file______________
import { socketTokenVerification } from './../../middleware/auth';
export default class {
constructor(io) {
this.io = io;
this.connections = {};
}
addConnection(socket) {
if (this.connections[socket.user_id]) {
this.socketDisconnect(this.connections[socket.user_id]);
}
this.connections[socket.user_id] = {
id: socket.id,
isAuthenticated: true,
user_id: socket.user_id
};
}
removeConnection(socket) {
delete this.connections[socket.user_id];
}
socketDisconnect(socket) {
if (this.io.sockets.connected[socket.id]) {
this.io.sockets.connected[socket.id].disconnect(true);
}
}
modelLoaded() {
const { io, connections } = this;
io.on('connection', socket => {
const authData = socketTokenVerification(socket);
if (authData.error) {
io.to(socket.id).emit('error', {
message: authData.message
});
this.socketDisconnect(socket);
return;
}
const { user_id } = authData;
socket.user_id = user_id;
this.addConnection(socket);
User.connected(socket.user_id);
socket.on('disconnect', () => {
this.removeConnection(socket);
User.disconnect(user_id);
this.socketDisconnect(socket);
Object.keys(io.sockets.connected).length);
});
Client side code.
import io from 'socket.io-client';
socket = io(ENDPOINT, {
transports: ['websocket'],
});
socket.on('connect', () => {
console.log('conected');
});
socket.on('disconnect', () => {
console.log('disconnected');
});
socket.on('reconnect', () => {
console.log('reconnect');
});
socket.on('receive_message', (receiveMsg) => {
console.log(recMsg, 'mes');
});
socket.on('error', (err) => {
console.log(err, 'err');
});
},
beforeDestroy() {
socket.disconnect(true);
},

socket.io - Client connects to two sockets by same server

I am trying to build socket connections between React client-side and Node.js server-side. But the server will host two sockets. Here is the server-side code
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(2893, {
path: "/ws",
resource: "/ws",
transports: ['websocket'],
pingTimeout: 5000
});
var redis = require('redis');
const subscriber = redis.createClient();
require('./server/route')(app, io);
require('./server/lib/subscriber')(require('socket.io').listen(server), subscriber);
The first socket connection is ok, but I wonder why the second one is not working (which is attached with listen(server). Here is subscriber module I wrote:
module.exports = (io, subscriber) => {
io.sockets.on('connection', (socket) => {
console.log(socket);
socket.on('room', (room) => {
socket.join(room);
});
});
subscriber.on('pmessage', (pattern, channel, message) => {
const msg = JSON.parse(message);
const idCallcenter = msg.idCallcenter;
return io.to(idCallcenter).emit('message', { type: channel, message: msg });
});
subscriber.psubscribe('*');
};
And the client-side React module
var socketOption = { path: "/ws", transports: ['websocket'] };
var socket = io("http://localhost:2893", socketOption);
var socket2 = io.connect("http://localhost:4004");
export default function (user) {
debugger
socket.user = user;
contact(socket);
notify(socket);
socket.on('connect', function () {
debug('socket connect', socket.id);
store.dispatch(connectNetworkSuccess());
socket.emit('user-online', {
idUser: user._id,
idCallcenter: user.idCallcenter,
email: user.email
});
});
socket2.on('connect', () => {
debug('Socket connected');
socket2.emit('room', user.idCallcenter);
});
socket2.on('message', (data) => {
debugger
debug('Socket message');
debug(data);
const type = data.type;
const message = data.message;
if (type === 'recordFetched') {
}
});
socket.emit('user-online', {
idUser: user._id,
idCallcenter: user.idCallcenter,
email: user.email
});
socket.on('disconnect', function (reason) {
debug('socket disconnect', reason);
store.dispatch(connectNetworkFailed());
});
}
The first socket (in port 2893) runs normally. Meanwhile, socket2 (in port 4004) does not connect. It does not jump into connection callback of both server and client sides. What did I do wrong here?
I solved the case myself. The working code on client side is:
export default function (user) {
debugger
var socketOption = { path: "/ws", transports: ['websocket'] };
var socket = env === "local" ? io("http://localhost:2893", socketOption) : io(window.location.origin, socketOption);
var socket2 = io.connect();
socket.user = user;
contact(socket);
notify(socket);
socket.on('connect', function () {
debug('socket connect', socket.id);
store.dispatch(connectNetworkSuccess());
socket.emit('user-online', {
idUser: user._id,
idCallcenter: user.idCallcenter,
email: user.email
});
});
socket2.on('connect', () => {
console.log('Socket connected');
socket2.emit('room', user.idCallcenter);
});
socket2.on('message', (data) => {
debugger
console.log('Socket message', data);
const type = data.type;
const message = data.message;
if (type === 'recordFetched') {
}
});
socket.emit('user-online', {
idUser: user._id,
idCallcenter: user.idCallcenter,
email: user.email
});
socket.on('disconnect', function (reason) {
debug('socket disconnect', reason);
store.dispatch(connectNetworkFailed());
});
}
The server did jump into connection callback, but not room callback. I suppose it is because the connect callback of client side was defined after the connection is made, so that it couldn't jump into it. This is my possibility. Am I right?

NodeJs Mocha Not Connecting to Database

I am trying to create some unit tests with Mocha and Chai but I am unable to connect to the mysql server. Here I have my unit test:
process.env.NODE_ENV = 'test';
let chai = require('chai');
let chaiHttp = require('chai-http');
let server = require('../app');
let should = chai.should();
chai.use(chaiHttp);
describe('API endpoint /authenticate', function () {
before((done) => {
/* Todo: Clean up Database*/
done()
});
it('should authenticate a user given CORRECT username/password', (done) => {
let user = {
username: 'ax850',
password: 'test'
};
chai.request(server)
.post('/api/authenticate')
.send(user)
.end((err, res) => {
res.should.have.status(200);
done();
});
done();
});
});
As you can see, I am doing a POST request. Then in the script where I handle this POST request, I am connecting to a mySQL server like so:
const db = require('./../../db_conn');
And in the db_conn I have:
const mysql = require('mysql');
const config = require('config.json')('./config.json');
let db;
const db_config = config.a_c.dbConfig;
function connectDatabase() {
if (!db) {
db = mysql.createConnection({
host: db_config.host,
user: db_config.user,
port: db_config.port,
database: process.env.NODE_ENV === 'test' ? db_config.db_test : db_config.db_dev,
//database: db_config.db_dev,
password: db_config.password
});
db.connect(function(err){
if(!err) {
console.log('Database is connected!');
} else {
console.log('Error connecting database!');
}
});
}
return db;
}
module.exports = connectDatabase();
However, when I run my test command: mocha --timeout 10000, it doesn't connect to the database. The mysql.createConnection runs unsuccessfully but doesn't give an error either. Any ideas? This works when I run the server without testing.
You are calling done before the request finishes.
chai.request(server)
.post('/api/authenticate')
.send(user)
.end((err, res) => {
res.should.have.status(200);
done();
});
// this is executed before chai.request is fulfilled
done();

Categories

Resources