Unit Testing HTTP Post request with database access - node.js

Hi I'm currently trying to learn and implement some unit testing for my HTTP Requests. currently I have a SQlite db setup, and a simple post request. This is the test I have written so far:
"use strict";
process.env.NODE_ENV = 'test';
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
const app = require('../../../app');
chai.request('http://localhost:8080')
.put('/tempValue')
.send({sensorid: '1', sensorValue: '25.00', timeRecorded: '2020-04-12 12:30'})
.then(function (res) {
expect(res).to.have.status(200);
})
.catch(function (err) {
throw err;
});
I seem to be getting a error that it is unable to open the database file. Currently I am just connecting to the database in the app.js file, using const dbPath = "./database/database.db"; and const dbConnection = sqlite.open(dbPath, { Promise });
I also seem to get errors about incorrect use of .catch? This is the error log:
(node:13952) UnhandledPromiseRejectionWarning: Error: SQLITE_CANTOPEN: unable to open database file
(node:13952) 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 unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13952) [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.
(node:13952) UnhandledPromiseRejectionWarning: AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 404
at D:\Uni Work\3rd Year\302CEM - Agile Development\Penguin Project\test\api\temperature\get.js:15:29
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13952) 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 unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Thanks for any help!
EDIT:
This is the particular post request I'm testing, it uses MQTT to check if the message being sent is to that topic structure, then inserts into the database.
app.ws.use(route.all('/tempValue', function (ctx){
client.on('message', async function(topic,message){
console.log(topic, message.toString());
if (topic === '302CEM/Penguin/Room1/Temperature'){
const SQL = "INSERT INTO sensorData (sensorid, sensorValue, timeRecorded) VALUES (?,?,?)";
try {
const temptostring = message.toString();
const db = await dbConnection;
await db.run(SQL, ["1",temptostring, moment().format('YYYY-MM-DD HH:mm')]);
ctx.websocket.send(temptostring);
} catch (err) {
console.log(err);
}
}
})
}));

Related

Unsure how to connect an api using nodejs

I'm trying to connect the openai api into my app but I'm not sure why it's not working. From my frontend, I have a createUserData that receives an input and then stores it to my MongoDB database. But now, I want to send that input that I received to the openai API and get a response based on what they said. I tried implementing it here but it crashed on me with this error:
UnhandledPromiseRejectionWarning: Error: Request failed with status code 401
at createError (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\adapters\http.js:322:11)
at IncomingMessage.emit (events.js:387:35)
at endReadableNT (internal/streams/readable.js:1317:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:17844) 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:17844) [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.
For some reason I crash when I try and call this API, am I doing it wrong?
Right now I just want to log whatever the response I get from the API, once I'm able to do that then I will store it to the database as well. But I can't even log it as I get an error. Here is my code:
const { Configuration, OpenAIApi } = require("openai");
// create new user data
const createUserData = async (req, res) => {
const {id, scores, transcript} = req.body
const user_id = req.user._id
console.log(user_id)
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
model: "text-davinci-002",
prompt: "Provide personal feedback for me and give me tips: " + transcript,
temperature: 0.7,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
console.log(response)
const newUserData = new UserData({
id: id,
scores: scores,
transcript: transcript,
user_id: user_id
})
// add doc to db
try {
await newUserData.save()
} catch (error) {
res.status(400).json({error: error.message})
}
console.log('POST:', newUserData)
return res.status(201).json({user_data: newUserData})
}

global Knex.raw is deprecated, use knex.raw (chain off an initialized knex object)

I am using knex and pg and I want to call a postgreSQL function from node.js preferably using knex.
i have used
const knex = require("knex");
exports.getAll = async (companyID) => {
console.log("from here", companyID);
const getAll = await databaseProvider
.knex("attendance")
.select(knex.raw("select * from get_allFromCompany('?')",[companyID]));
return databaseProvider.executeQuery(getAll).then((result) => {
return result.rows;
});
But I am getting error:
global Knex.raw is deprecated, use knex.raw (chain off an initialized knex object)
(node:25) UnhandledPromiseRejectionWarning: Error: Unable to acquire a connection
at Client_PG.acquireConnection (/app/node_modules/knex/lib/client.js:340:13)
at Runner.ensureConnection (/app/node_modules/knex/lib/runner.js:264:8)
at Runner.run (/app/node_modules/knex/lib/runner.js:26:12)
at Builder.Target.then (/app/node_modules/knex/lib/interface.js:19:43)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:25) 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: 3)
};
I have also tried several other hacks but I am unable to do so.
My sql query is
SELECT * FROM get_allFromCompany('1');
Can someone help me out?
You need to initialize knex instance with dialect are you using and then create a query with bindings with knex and only after that you can use DB driver to execute it.
const knex = require("knex")({client: 'pg'});
exports.getAll = async (companyID) => {
console.log("from here", companyID);
const getAllQuery = databaseProvider
.knex("attendance")
.select(knex.raw("select * from get_allFromCompany('?')",[companyID])).toSQL().toNative();
return databaseProvider.executeQuery(getAllQuery .sql, getAllQuery .bindings).then((result) => {
return result.rows;
});

UnhandledPromiseRejectionWarning: TypeError: res.send is not a function

I am trying to get this aligoapi npm package to work.
when i send request it's showing error
here is my code:
const aligoapi = require('aligoapi');
var AuthData = {
key: '<my_key>',
user_id: '<my_id>',
}
var send = (req, res) => {
console.log('check')
aligoapi.send(req, AuthData)
.then((r) => {
console.log('check1')
res.send(r)
})
.catch((e) => {
console.log('check2')
res.send(e)
})
}
console.log('check3')
var number = {
body: {
sender: '01022558877',
receiver: '01081079508',
msg: 'test msg'
}
}
const result = send(number,'err')
console.log(result)
and this is the terminal output:
justin#Justinui-MacBookPro examples % node test.js
check3
check
undefined
check2
(node:94270) UnhandledPromiseRejectionWarning: TypeError: res.send is not a function
at /Users/justin/Downloads/node.js_exampl/examples/test.js:19:11
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:94270) 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: 3)
(node:94270) [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.
justin#Justinui-MacBookPro examples %
here i notice my request isn't actually being sent because it's returning undefined

Trying to update a table - Error: Unhandled promise rejection node.js

I'm trying to update a user with a hashed password when I start the app.
So I wrote this in app.js:
try {
bcrypt.hash("ADMIN", saltRounds, async function(err, hash) {
queryUpdate = await Utilisateur.query().patch({
MOTPASS: hash
}).where('NOGENE', 4219)
.catch(console.log('err'));
});
} catch (err) {
errorDbHandler.sendErrorHttp(err, res);
}
And I got this error:
(node:6800) UnhandledPromiseRejectionWarning: TypeError: Utilisateur.query is not a function
at D:\Project\***\backend\app.js:48:37
(node:6800) 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:6800) [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.
use this code for catching the error:
try {
bcrypt.hash("ADMIN", saltRounds, async function(err, hash) {
try {
queryUpdate = await Utilisateur.query().patch({
MOTPASS: hash
}).where('NOGENE', 4219);
} catch (e) {
console.log(e);
}
});
} catch (err) {
errorDbHandler.sendErrorHttp(err, res);
}
you tried to mix "then().catch()" with "await", which will not work.

Chrome launcher exits with UnhandledPromiseRejectionWarning

I am trying to set up chrome-launcher to output all console messages to terminal. My code looks like this
const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');
(async function() {
async function launchChrome() {
return await chromeLauncher.launch({
chromeFlags: [
'--window-size=1200,800',
'--user-data-dir=/tmp/chrome-testing',
'--auto-open-devtools-for-tabs'
]
});
}
const chrome = await launchChrome();
const protocol = await CDP({
port: chrome.port
});
const {
DOM,
Network,
Page,
Runtime,
Console
} = protocol;
await Promise.all([Network.enable(), Page.enable(), DOM.enable(), Runtime.enable(), Console.enable()]).catch(console.log);
// REMARKS: messageAdded is fired every time a new console message is added
Console.messageAdded((result) => {
console.log(result);
});
})();
I copied some of this from the question here: How to get console.log output in Terminal via Headless Chrome Runtime.evaluate
When I try to navigate to a page, none of the console messages show up in the terminal, and the chrome-launcher exits with the following error:
(node:14531) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:64656
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1083:14)
(node:14531) 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: 1)
(node:14531) [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.

Resources