Protractor - "Failed: each key must be a number of string; got undefined" - protractor

this program is to retrieve the value from other .js file using Protractor.
FirstConnectDatabase.js - establish the DB connection and Query.
spec.js - retrieve the result from the above .js file.
getting the below Error
Failed: each key must be a number of string; got undefined
Can anyone help me on this.
**spec.js**
var dbConnect = require('./FirstConnectDatabase.js');
var AptNbr = new dbConnect;
var readAptNbr = AptNbr.Apts;
console.log('Enter the order #'+readAptNbr);
**FirstConnectDatabase.js**
var retrieveAptNbr = function mySQLDatabase()
{
var mysql = require('../../node_modules/mysql');
var Aptnumber="";
var connection = mysql.createConnection({
host: 'local',
user :'user',
password :'password',
database:'DB'
});
connection.connect(function(err){
if(err){
console.log("Error"+err)
}else{
console.log('DB is connected');
}
});
connection.query("select * from XXXX",function(err,rows) {
if (!err)
{
console.log("result is :", rows[0].AptNo);
var Apts = (function() {
var on = rows[0].Aptnumber;
return parseInt(on);
}());
}else{
console.log("Error"+err)
}
});
};
module.exports=retrieveAptNbr;

This error comes when we are fetching a string value from other JS file, where string is not present or may be our fetching statement is incorrect. In your case you also fetching value in 'on' variable, check if it is getting some string value or not.

Related

jsforce ignoring callback functions?

I tool the code right out of the docs, but it's like it completely ignores the existence is the call back functions:
var jsforce = require('jsforce');
var conn = new jsforce.Connection({
// you can change loginUrl to connect to sandbox or prerelease env.
loginUrl : 'https://ivytechfoundation--ucidev.my.salesforce.com'
});
conn.login('xxxxxx#ivytech.edu.uci.ucidev', 'xxxxxxxxTOjhPejiRZ1KWox4AmYOPzqu', function(err, userInfo) {
console.error('1');
// if (err) { return console.error(err); }
console.error(err);
console.error(userInfo);
// Now you can get the access token and instance URL information.
// Save them to establish connection next time.
console.log(conn.accessToken);
console.log(conn.instanceUrl);
// logged in user property
console.log("User ID: " + userInfo.id);
console.log("Org ID: " + userInfo.organizationId);
// ...
});
Any ideas? It never hits '1'
There seems to be a bug. I couldn't make it work either, but this works:
conn
.login(sfUserName, sfPassword + sfToken)
.then((userInfo) => { // your code here

How to fix a Wait condition error?

I have a browser.wait() in an E2E test which is invoking a function defined in protractor.config.js file. When running the test, I get the following error:
Failed: Wait condition must be a promise-like object, function, or a Condition object
FYI - the function defined in protractor.config.js contains an If-condition which I need for two cases. When I remove the If-condition, the test runs fine. The function returns a: deferred.promise
What does this exactly means and how to fix it? Have been searching, but unfortunately can't anything related to it.
Function in protractor.config.js:
checkMail: function(user, subjectSent) {
const deferred = protractor.promise.defer();
var usermail;
var mailsubject;
var count = 0;
mailListener.on("mail", function(mail, seqno, attributes) {
var mailuid = attributes.uid;
var toMailbox = '[Gmail]/All Mail';
var i = ++count;
user = mail.to[0].address;
mailsubject = mail.subject;
if (i > 2) {
mailListener.stop();
return;
}
deferred.fulfill(mail);
});
if ((user === usermail) && (subjectSent === mailsubject)) {
return deferred.promise;
}
}
E2E it-function:
it("It should do xxxxxxx", (done) => {
browser.wait(browser.params.checkMail('user_email#yyyyy.com', 'Email subject'))
.then((email) => {
expect(email['subject']).toEqual("Email subject");
expect(email['headers'].to).toEqual( 'user_email#yyyyy.com' );
});
done();
});

URL works until I set it to process.env.MONGOLAB_URI via command line

I've been experimenting with the API of flickr and am looking to deploy the application to Heroku now that I am finished. In order to do this, since I'm using MongoDB, I'm trying to get it to run with mLab. I can log into the shell just fine, I can get the entire thing to run when I use the URL to the database as a string, but suddenly when I assign that URL to process.env.MONGOLAB_URI with SET MONGOLAB_URI="mongodb://dbuser:dbpassword#ds041506.mlab.com:41506/flick
r_image_search" (I'm using Windows 10) in the local command line and try to use it, it stops working. The error message I'm getting is "Error: invalid schema, expected mongodb". Even when I used console.log(url) it returned "mongodb://dbuser:dbpassword#ds041506.mlab.com:41506/flickr_image_search" (I guarantee the username and password I used in the command line are both absolutely correct considering I literally copy+pasted the URL I used that worked into the command line) as I would expect. The IDE I'm using is Visual Studio Code and I haven't been using the heroku mLab add-on to run this but my database on the website itself. I'm out of ideas and can use some help. Here's each relevant file of code I'm using for the application:
app.js
var express = require('express');
var app = express();
var flickr = require('./flickr.js');
var mongo = require('mongodb').MongoClient;
var path = require('path');
var url = process.env.MONGOLAB_URI;
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
var mins = today.getMinutes();
var hr = today.getHours();
today = month + '/' + day + '/' + year + ' ' + hr + ':' + mins;
var obj;
var search;
app.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/latest', function(req, res){
mongo.connect(url, function(err, db){
if(err) throw err;
var theCollection = db.collection('flickr_image_search');
theCollection.find({}).toArray(function(err, docs){
if(err) throw err;
search = docs;
return docs;
});
db.close();
});
res.send(search);
});
app.get(['/search/:text/:offSet2', '/search/:text'], function(req, res){
var lookInIt = req.params.text;
var listLength = req.params.offSet2;
var searched = flickr.search(lookInIt, listLength || 10);
obj = {
query: lookInIt,
offSet: listLength,
date: today
};
mongo.connect(url, function(err, db){
if(err) throw err;
var imageSearch = db.collection('flickr_image_search');
imageSearch.insert(obj);
db.close();
});
res.send(searched);
});
var port = 3000 || process.env.PORT;
app.listen(port, process.env.IP, function(){
console.log('LISTENING');
});
flickr.js
var private = require('./private');
var Flickr = require("flickrapi"),
flickrOptions = {
api_key: private.key,
secret: private.secret
};
var obj;
function search (query, offSet) {
Flickr.tokenOnly(flickrOptions, function (err, flickr) {
if (err) throw err;
flickr.photos.search({
text: query,
page: 1,
per_page: offSet,
sort: "relevance"
}, function (err, result){
if(err) throw err;
result = result.photos.photo;
for(var key in result){
var picUrl = 'https://farm' + result[key]["farm"] + '.staticflickr.com/' + result[key]["server"] + '/' + result[key].id + '_' + result[key].secret + '.jpg'
result[key].picUrl = picUrl;
var userUrl = 'https://www.flickr.com/photos/' + result[key].owner + '/' + result[key].id;
result[key].userUrl = userUrl;
delete result[key]["ispublic"];
delete result[key]["isfriend"];
delete result[key]['isfamily'];
delete result[key]['id'];
delete result[key]['owner'];
delete result[key]['server'];
delete result[key]['farm'];
delete result[key]['secret'];
}
obj = result;
});
});
return obj;
}
module.exports.search = search;
index.html
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<title>flickr Image Search</title>
<div class='container'>
<h1 class='text-center'>Flickr Image Search</h1>
<h3 class='well'>To get a series of URLs for images, type 'search/whatever-you-want-to-search/the-amount-of-photos-you-want-returned' in the address bar after 'someWebsite.com/'.
If you want to see the most latest searches that were searched, instead of 'search/whatever-you-want-to-search/the-amount-of-photos-you-want-returned' type 'latest'.
When you find the URL that you want, just copy+paste!</h3>
<p class=lead>This application is purely functional, so chances are the queries won't return clean.</p>
<p>This is an application that searches through the photos of Flickr, using its API.</p>
</div>
Heroku uses MONGODB_URI, but you have MONGOLAB_URI.
This could explain why the string works but the environment variable doesn't.
Try typing this in your shell: heroku config
Find the heroku config variable. I would venture to guess it is MONGODB_URI and not MONGOLAB_URI.
If this is the case, reset your environment and heroku config variable to use MONGODB_URI.
You said in a comment: "I'm not sure how to check it on Heroku, especially since the app doesn't want to run on there. Heroku has been giving me troubles when deploying applications in general."
To check your config variables, you can type heroku config in your shell, or you can navigate to your apps dashboard. Click on Settings. Click on Reveal Config Vars.
While you are in the dashboard, you can provision the mLab Add-on that Heroku provides by clicking on the Resources tab. Then in the Add-on's search box, type in mLab MongoDB.
Click on it. This will take you to mLab's GUI where you can view and manage your collections.
If you are wondering what the server setup looks like, see the code below. This will connect to both your local and mLab db where appropriate.
if(process.env.MONGODB_URI) {
mongoose.connect(process.env.MONGODB_URI);
}else {
mongoose.connect(db, function(err){ //db = 'mongodb://localhost/yourdb'
if(err){
console.log(err);
}else {
console.log('mongoose connection is successful on: ' + db);
}
});
}
It's been helpful to me to install dotenv (https://www.npmjs.com/package/dotenv), require('dotenv'), then dotenv.load() before declaring process.env variables. Now stuff in my .env file is read in where it wasn't before. thx.

TypeError: Cannot read property 'cookie' of undefined

When calling my User.create method in my Sails.js app, I get the following error:
/Users/user/code/bt/tgein/node_modules/mongodb-core/lib/topologies/server.js:779
catch(err) { process.nextTick(function() { throw err}); }
Here is my User controller in its entirety.
User.create(req.params.all(), function userCreated(err, user) {
// var userid = user.id;
// console.log(userid);
if(err) {
console.log(err);
req.session.flash = {
err: err.ValidationError
}
return res.redirect('/user/loginDetails');
}
var oldDateObj = new Date();
var newDateObj = new Date(oldDateObj.getTime() + 60000);
req.session.cookie.expires = newDateObj;
req.session.authenticated = true;
console.log(req.session);
// res.redirect('/user/profileSelection/?id=' + user.id);
// Saves user data into session variable
req.session.user = user;
res.redirect('/user/profileSelection/');
});
apparently the session value is undefined for the request. This seems symptomatic of something basic that isn't happening, but I don't know what that is.
req.session.cookie is not defined and you are trying to set a value to an undefined object.
var oldDateObj = new Date();
var newDateObj = new Date(oldDateObj.getTime() + 60000);
if(!req.session.cookie)
req.session.cookie = {};
req.session.cookie.expires = newDateObj;
I think the problem is not of session, as session is always retained/defined within an sails app. May be the issue exists, when you trying to save the data.
The problem was I had the session store trying to go through the production adapter in my sessions.js on my local app, which caused the req.session to fail.

getting data from mongodb collection

Trying to get some messages from a db collection, I've tried that code (server side):
MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) {
if(err) throw err;
var history="";
var collection = db.collection('gt-chat');
console.log("******************************Printing docs from Cursor Each")
collection.find({}, {_id: 0}).sort({$natural: 1}).limit(20).each(function(err, doc) {
console.log(doc)
if(doc != null) {
console.log("Doc from Each ");
history=history+console.dir(doc)+"\r\n";
console.dir(doc);
}
});
console.log("/////////////HISTORY//////////////////");
console.log(history); ; // data is shown there under the shell console, all is fine !
socket.emit('updatechat', 'SERVER', history); // should send the messages using socket
});
and then on the client side, I've tried :
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
date = new Date;
h = date.getHours();
if (h<10) {
h = "0"+h;
}
m = date.getMinutes();
if (m<10) {
m = "0"+m;
}
s = date.getSeconds();
if (s<10) {
s = "0"+s;
}
var time = h+":"+m+":"+s;
$('#conversation').append('<b><strong>' + time + '</strong> '+username + ':</b> ' + data + '<br>');
});
which doesn't show anything as expected :(
I am quite sure about the updatechat function because I can get message with it, as I've tried:
socket.emit('updatechat', 'SERVER',"this is history"); // < message is well sent, so no problem there!
but I don't get the all history.
So the goal is to get some messages from a mongodb collection and to display them under the browser using socket emit
Under the shell, to debug, it's showing:
Doc from Each { message: '<strong>12:16:27</strong><span style=\'color:#2fed7e\'><b>guibs</b>< /span><em> hum</em>' } { message: '<strong>12:16:27</strong><span style=\'color:#2fed7e\'><b>guibs</b>< /span><em> hum</em>' }
So, data and messages exist, but I can't read them from the browser. The shell says: 'history is not defined' ! What is wrong with concatenation? And my variable declaration? I don't understand, thanks for your help!