How to test a promise that connects to RabbitMQ? - javascript

Hi I'm using Chai and trying to test a custom function that connects to RabbitMQ passing a wrong host:
connect(host) {
return new Promise((resolve, reject) => {
amqp.connect(host)
.then((conn) => {
resolve(conn);
})
.catch((err) => {
throw new Error(err);
});
});
}
If the connection fail I throw a Error, so I'm testing it like this:
it('shouldnt connect to RabbitMQ service successfully with the wrong host.', async () => {
const result = await rabbitmqmailer.connect('amqp://wronghost');
expect(result).to.equal(Error);
});
The connection fails and throws a error but my test is not testing that, simply I got the exception on my terminal:
RabbitMQMailer component.
RabbitMQMailer configuration information.
✓ should test rabbitmqmailer host configuration.
✓ should test rabbitmqmailer queue configuration.
✓ should get rabbitmqmailer empty emailContent value after make a new instance.
✓ should get rabbitmqmailer empty emailContentConsumed value after make a new instance.
✓ resolves
✓ should connect to RabbitMQ service successfully with the correct host. (60ms)
Unhandled rejection Error: Error: getaddrinfo EAI_AGAIN wronghost wronghost:5672
at _amqplib2.default.connect.then.catch.err (/home/ubuntu/Desktop/easy-tracking/backend/src/components/rabbitmqmailer/rabbitmqmailer.dal.js:1:11069)
at tryCatcher (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/promise.js:690:18)
at _drainQueueStep (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/async.js:17:14)
at processImmediate (timers.js:632:19)
1) shouldnt connect to RabbitMQ service successfully with the wrong host.
I tried catching the exception on a trycatch block but it's the same issue.
EDIT: I got this error on terminal after changing my test to:
it('shouldnt connect to RabbitMQ service successfully with the wrong host.', async (done) => {
const result = await rabbitmqmailer.connect('amqp://wronghost');
expect(result).to.be.an.instanceof(Error);
done();
});
(node:18911) UnhandledPromiseRejectionWarning: Error: Error: getaddrinfo EAI_AGAIN wronghost wronghost:5672
at _amqplib2.default.connect.then.catch.err (/home/ubuntu/Desktop/easy-tracking/backend/src/components/rabbitmqmailer/rabbitmqmailer.dal.js:1:11475)
at tryCatcher (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/promise.js:690:18)
at _drainQueueStep (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/async.js:147:5)
at Immediate.Async.drainQueues (/home/ubuntu/Desktop/easy-tracking/backend/node_modules/amqplib/node_modules/bluebird/js/release/async.js:17:14)
at processImmediate (timers.js:632:19)
(node:18911) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:18911) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
1) shouldnt connect to RabbitMQ service successfully with the wrong host.
1) RabbitMQMailer component.
RabbitMQMailer configuration information.
shouldnt connect to RabbitMQ service successfully with the wrong host.:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/ubuntu/Desktop/easy-tracking/backend/src/components/rabbitmqmailer/rabbitmqmailer.test.js)

You are not properly failing. You forgot about the reject. Do this instead:
connect(host) {
return new Promise((resolve, reject) => {
amqp.connect(host)
.then((conn) => {
resolve(conn);
})
.catch((err) => {
reject(new Error(err)); // Pass the error to reject
});
});
}
In your test, use instanceof to match the Error that is returned:
it('shouldnt connect to RabbitMQ service successfully with the wrong host.', async () => {
const result = await rabbitmqmailer.connect('amqp://wronghost');
expect(result).to.be.an.instanceof(Error);
});
Also I don't know what you are using for testing, but if it is jest, then this link might help you properly test the promise.
EDIT: Actually nvm. I see you are using Chai

You need to reject the Promise.
connect(host) {
return new Promise((resolve, reject) => {
amqp.connect(host)
.then((conn) => resolve(conn))
.catch((err) => reject(new Error(err));
});
}
And the test
it('shouldnt connect to RabbitMQ service successfully with the wrong host.', () => {
return rabbitmqmailer.connect('amqp://wronghost')
.then(() => { assert.fail('was not supposed to succeed'); })
.catch((err) => { expect(err).to.be.an.instanceof(Error); })
})

You usually want your tests to be isolated. I would recommend mocking your amqp object and expect that the connect method is being called.
It's important that you try and understand the real connect method before designing the mock
You can use a mocking framework like https://sinonjs.org/

Finally I found the way to test it
it('shouldnt connect to RabbitMQ service successfully with the wrong host.', (done) => {
(async () => {
try {
await rabbitmqmailer.connect('amqp://wronghost');
} catch (error) {
chai.assert.typeOf(error, 'error');
} finally {
done();
}
})();
});
But there's some strange issue, if I change the type like a 'string' for example, it tells me:
(node:26053) UnhandledPromiseRejectionWarning: AssertionError: expected [Error: Error: getaddrinfo EAI_AGAIN wronghost wronghost:5672] to be a string
But ! the test passes successfully :
✓ shouldnt connect to RabbitMQ service successfully with the wrong host.
I don't know why it's happen but it works anyway, thanks for the help.

Related

How to Catch Error: connect ECONNREFUSED at TCPConnectWrap.afterConnect [as oncomplete]

I am using #nestjs/axios in my NestJS backend application to call an endpoint as bellow:
this.httpService.get('some url').pipe(
catchError(e => {
throw new InternalServerErrorException('error');
}),
map(res => {
console.log('succeeded');
})
);
The problem is that when the endpoint is available then the succeeded will be reached, but when the endpoint is not available the catchError is never reached and succeeded neither.

How can I solve login error on discord.js [duplicate]

This question already has answers here:
Why am I getting a ReferenceError: AbortController is not defined in Discord.js v13?
(3 answers)
Closed 1 year ago.
const {Client, Intents} = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once('ready', () => {
console.log('Ready!');
});
client.login(token);
I have this code, every time i try to run it returns me the same error:
(node:13284) UnhandledPromiseRejectionWarning: ReferenceError:
AbortController is not defined
at RequestHandler.execute (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\rest\RequestHandler.js:172:15)
at RequestHandler.execute (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\rest\RequestHandler.js:176:19)
at RequestHandler.push (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\rest\RequestHandler.js:50:25)
at async WebSocketManager.connect (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\client\websocket\WebSocketManager.js:128:9)
at async Client.login (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\client\Client.js:245:7)
(Use node --trace-warnings ... to show where the warning was
created) (node:13284) UnhandledPromiseRejectionWarning:
Unhandled promise rejection. This error originated either by throwing
inside of an async function without a catch block, or by rejecting a
promise which was not handled with .catch(). To terminate the node
process on unhandled promise rejection, use the CLI flag
--unhandled-rejections=strict (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 2) (node:13284) [DEP0018] DeprecationWarning: Unhandled
promise rejections are deprecated. In the future, promise rejections
that are not handled will terminate the Node.js process with a
non-zero exit code.
Dont know how to fix it. I tried and investigate on the documentation but cant find the solution.
I've added this line to my code to find the error:
process.on('unhandledRejection', error => {
console.error('Unhandled promise rejection:', error);
});
Getting this:
{ code: 500, method: 'get', path: '/gateway/bot', requestData:
{ json: undefined, files: [] } }
The AbortController package was introduced in Node.js v16 (?). So you need to upgrade your Node.js version. Discord.js v13 requires you to use Node.js v16 and higher as stated in their documentation.
Depending on your operating system, you can either install 64bits or 32bits version of Node.js. Head over to the official website and download 16.8.x (Current, Latest Features) Windows installer.
After installation, verify the version by typing node -v in your console.

Error trying to do search for records matching criteria with MongoDB

I am taking a training course, on Udemy, and it had backend code already written, as the course is purely about frontend development. It uses a very simple MongoDB database that I created. I determined that MongoDB version 4.0.10 is installed on my computer, in case that's relevant. When trying to perform a query for matching records, I get the following error:
UnhandledPromiseRejectionWarning: MongoError: FieldPath field names may not start with '$'.
at MessageStream.messageHandler (I:\DEV\Training\React For the Rest of Us\backend-api\node_modules\mongodb\lib\cmap\connection.js:268:20)
at MessageStream.emit (events.js:315:20)
at processIncomingData (I:\DEV\Training\React For the Rest of Us\backend-api\node_modules\mongodb\lib\cmap\message_stream.js:144:12)
at MessageStream._write (I:\DEV\Training\React For the Rest of Us\backend-api\node_modules\mongodb\lib\cmap\message_stream.js:42:5)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at TLSSocket.ondata (internal/streams/readable.js:719:22)
at TLSSocket.emit (events.js:315:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
(node:51960) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To
terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
After looking into the backend code, I found the following code that is being used to perform the query/search, and I did notice that there are $ symbols in various places.
Post.search = function(searchTerm) {
return new Promise(async (resolve, reject) => {
if (typeof(searchTerm) == "string") {
let posts = await Post.reusablePostQuery([
{$match: {$text: {$search: searchTerm}}},
{$sort: {score: {$meta: "textScore"}}}
])
resolve(posts)
} else {
reject()
}
})
}
What exactly is wrong and how do I fix it?
Identical error here. Searching from react using axios in the main app-very simple(supposed to be). It's indicative that in my case when trying to search- "open search mode" from react", mongodb server crashes with mentioned error:
f:\PrgsReact\SimplePost\backend-api\node_modules\mongodb\lib\cmap\connection.js:268
callback(new MongoError(document));
MongoError: FieldPath field names may not start with '$'.
etc..
I'm tried to change npm ver of mongodb and axios inter alia. Thanks.

Cannot connect to MySQL database with Node.js

My app has to connect to a mysql database but i am stuck just in that moment i cant connect it, im using a method that transforms callbacks code to promise code thats the reason i need to use async and await also the man of the tutorial doesnt have any error i guess because he has diferent terms on the keys.js, he is on linux, root user and also he has a password, things that i dont have. I really need hel thank you.
This is the code that is giving problems:
const express= require('express');
const router= express.Router();
const pool = require('../database');
router.get('/add', (req,res) =>{
res.render('casas/add');
});
router.post('/add', async (req,res) => {
const {titulo, precio, direccion, numhab, superficie} = req.body;
const nuevoPiso={
titulo,
precio,
direccion,
numhab,
superficie
};
await pool.query('INSERT INTO PISOS set ?', [nuevoPiso]);
res.send('recibido');
});
module.exports=router;
The problem is on the await line because if I delete that and the async word it works perfectly but obviously without that I cant send the elements to the database. The error that gives me the terminal is this:
(node:9548) UnhandledPromiseRejectionWarning: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'Axell'#'localhost' (using password: NO)
at Handshake.Sequence._packetToError (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Handshake.ErrorPacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\sequences\Handshake.js:123:18)
at Protocol._parsePacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
--------------------
at Protocol._enqueue (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:116:18)
at Pool.getConnection (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Pool.js:48:16)
at Pool.query (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Pool.js:202:8)
at internal/util.js:297:30
at new Promise (<anonymous>)
at Pool.query (internal/util.js:296:12)
at C:\Users\Axell\Desktop\node-sql-app\src\routes\casas.js:20:15
at Layer.handle [as handle_request] (C:\Users\Axell\Desktop\node-sql-app\node_modules\express\lib\router\layer.js:95:5)
(node:9548) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:9548) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
POST /casas/add - - ms - -
(node:9548) UnhandledPromiseRejectionWarning: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'Axell'#'localhost' (using password: NO)
at Handshake.Sequence._packetToError (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Handshake.ErrorPacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\sequences\Handshake.js:123:18)
at Protocol._parsePacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
--------------------
at Protocol._enqueue (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Connection.js:116:18)
at Pool.getConnection (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Pool.js:48:16)
at Pool.query (C:\Users\Axell\Desktop\node-sql-app\node_modules\mysql\lib\Pool.js:202:8)
at internal/util.js:297:30
at new Promise (<anonymous>)
at Pool.query (internal/util.js:296:12)
at C:\Users\Axell\Desktop\node-sql-app\src\routes\casas.js:20:15
at Layer.handle [as handle_request] (C:\Users\Axell\Desktop\node-sql-app\node_modules\express\lib\router\layer.js:95:5)
(node:9548) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
POST /casas/add - - ms - -
I dont know where the error is maybe on my keys.js where i have this im on windows that is my username but I dont have a password:
module.exports={
database:{
host:'localhost',
user:'Axell',
database: 'casas',
password: ''
}
};
Here you can download the whole app it is unfinished because I cant continue due to this error: https://mega.nz/#!LAwgwAQK!OiuBqH4qxyT5CW2xRSUXdmhpfRyTtf3TobmYw-NqIic
Thank you so much!
The issue you are having is unrelated to async/await.
The credentials to MySQL incorrect. This could be an incorrect username, an incorrect password or perhaps you did not grant the Axell permission to access the casas database.
Given that you're on localhost, you can test this without localhost. Just try logging on with the same credentials with some other mysql tool (such as the mysql) tool, and you should get a similar error.

I Got A "UnhandledPromiseRejectionWarning" And A "DeprecationWarning" When Trying To Run The Code For The Bot, Any Solution To Fix This Problem?

Im Trying To Make A Discord Bot For A Server, I Entered "node ." into the terminal to run the bot and i got this error:
(node:17632) UnhandledPromiseRejectionWarning: Error: Incorrect login details were provided.
at WebSocketConnection.<anonymous> (C:\Users\Thela\code\node_modules\discord.js\src\client\ClientManager.js:48:41)
at Object.onceWrapper (events.js:300:26)
at WebSocketConnection.emit (events.js:210:5)
at WebSocketConnection.onClose (C:\Users\Thela\code\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:390:10)
at WebSocket.onClose (C:\Users\Thela\code\node_modules\ws\lib\event-target.js:124:16)
at WebSocket.emit (events.js:210:5)
at WebSocket.emitClose (C:\Users\Thela\code\node_modules\ws\lib\websocket.js:191:10)
at TLSSocket.socketOnClose (C:\Users\Thela\code\node_modules\ws\lib\websocket.js:850:15)
at TLSSocket.emit (events.js:215:7)
at net.js:658:12
(node:17632) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either
by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:17632) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
In The Terminal.
This Is The index.js file:
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.content === '!ping') {
message.channel.send('Pong.');
}
});
client.login(config.token);
And Here Is The config.json:
{
"prefix": "!",
"token": "7F2x4ct0AMuBeJKZUGmtIz_RZVKve-N4"
}
i realised i didnt put the full error
oops
What you are using as "token" is actually your client secret, the token should look something like this:
NjQwOTM2MjE3MTg5Mjg1ODg4.XcGSOQ.3dgX4GbvEDZKYHnCb6nJORuvL1w

Categories