I made a script in Javascript (for phantomjs) to automate tests in a website.
I would like to count the errors encountered.
With this script, I get the error : "nbe variable unknown".
I understand that try... catch works in a specific way but I don't know what to do.
How can I modify my script to make it work?
Thank you
var nbe = 0;
var err = 0;
function next_page() {
page.evaluate(function() {
try {
document.querySelector('input[name="cc"]').click();
} catch (e) {
nbe++;
console.log('Error');
err = 1;
}
});
var k = i + 1 - nbe;
if (err == 0) console.log('Test ' + k + ' done');
i++;
if (i < links.length) setTimeout(handle_page, 1500);
else {
console.log('Errors : ' + nbe);
phantom.exit();
}
}
You could do something like the following:
var nbe = 0;
var err = 0;
var errors = [];
function next_page() {
page.evaluate(function() {
try {
document.querySelector('input[name="cc"]').click();
} catch (e) {
nbe++;
console.log('Error');
err = 1;
errors.push(e);
}
});
var k = i + 1 - nbe;
if (err === 0) {
console.log('Test ' + k + ' done')
};
i++;
if (i < links.length) {
setTimeout(handle_page, 1500);
} else {
for(var j = 0; j < errors.length; j++){
console.log(errors[j]);
}
phantom.exit();
}
}
Related
async function getjsondata() {
try {
state = await fetch('https://covid.ourworldindata.org/data/owid-covid-data.json');
data = await state.json();
} catch (err) {
console.log(err);
}
}
var sumy = 0;
var tt_list = [];
async function getmonthnewcases() {
await getmonthsum();
await getjsondata();
await getCountry();
try {
for (let i = 0; i < 12; i++) {
for (let z = listy[i]; z <= listy[i + 1]; z++) {
for (key in data[isocount]["data"][z]) {
if (data[isocount]["data"][z].hasOwnProperty(key) == true) {
sumy += Number(data[isocount]["data"][z]["total_cases_per_million"]);
tt_list[i] = sumy;
} else if (typeof data[isocount]["data"][z]["total_cases_per_million"] === "undefined") {
data[isocount]["data"][z]["total_cases_per_million"] = sumy;
continue;
}
if (z == data[isocount]["data"].length - 1) {
break;
}
console.log(data[isocount]["data"][z]["date"], sumy, data[isocount]["data"][z]["total_cases_per_million"]);
}
}
}
console.log(tt_list);
} catch (err) {
console.log(err);
}
}
So this is how the code looks like am having trouble solving the issue of undefined in a particular month date from the api call, i have tried so many other options but nothing seems to be working please i nned some help
First is seems that you have some errors in the code,
You are not returning anything from getjsondata.
And you are not using the results in getmonthnewcases
(See code comments)
async function getjsondata() {
try {
state = await fetch('https://covid.ourworldindata.org/data/owid-covid-data.json');
return await state.json(); //<-- here
} catch (err) {
console.log(err);
}
}
var sumy = 0;
var tt_list = [];
async function getmonthnewcases() {
await getmonthsum();
const data = await getjsondata(); //<-- and here
await getCountry();
try {
for (let i = 0; i < 12; i++) {
for (let z = listy[i]; z <= listy[i + 1]; z++) {
for (key in data[isocount]["data"][z]) {
if (data[isocount]["data"][z].hasOwnProperty(key) == true) {
sumy += Number(data[isocount]["data"][z]["total_cases_per_million"]);
tt_list[i] = sumy;
} else if (typeof data[isocount]["data"][z]["total_cases_per_million"] === "undefined") {
data[isocount]["data"][z]["total_cases_per_million"] = sumy;
continue;
}
if (z == data[isocount]["data"].length - 1) {
break;
}
console.log(data[isocount]["data"][z]["date"], sumy, data[isocount]["data"][z]["total_cases_per_million"]);
}
}
}
console.log(tt_list);
} catch (err) {
console.log(err);
}
}
Below is my gulp task:
var validateCss = require("css-validator");
gulp.task("cssvalid", async function () {
var files = glob.sync("src/styles/*.css");
for (var i = 0; i < files.length; i++) {
var filesource = fs.readFileSync(files[i], "utf8");
checks(filesource);
}
});
function checks(filesource) {
validateCss({ text: filesource, profile: "css3svg" }, function (err, data) {
if (data.errors.length == 0) {
console.log("Success: " + files[i]);
console.log("No errors or warnings\n");
} else {
data.errors.forEach(function (error) {
console.log("Error: " + files[i] + ": line " + error.line);
console.log(error.message + "\n");
});
}
});
}
Before my validateCss function's callback gets called, it goes for next for loop, so that it wont throw css validation error properly
I am still pretty new to this, so forgive me if I dont' say this correctly. We have an array.reduce that calls a method with a returning promise that iterates through a list of files and post results to the db. Everything was working great, until it ran into a field that had an apostrophe in it and then the db insert fails. This is the field value. 'Expected 100002822' to be 100002822.'
I tried adding a replaceAll on the field and now get an error in the array.reduce.
Here is the .reduce
console.log('Found test results in ' + matches.length + ' files. Parsing and posting to the database now...');
var startTime = moment();
var parser = new Parser();
matches.reduce(function (p, val) {
return p.then(function () {
return parser.parseResults(val);
});
}, Promise.resolve()).then(function (finalResult) {
var endTime = moment();
var testDuration = moment.duration(endTime.diff(startTime));
console.log(chalk.blue('*** File parsing time: ' + testDuration.humanize() + ' ***'));
if (finalResult.insertSuccess == matches.length) {
var publishOut = {
totalFiles: matches.length,
totalTests: 0,
totalTestsSuccess: 0,
totalTestsFailed: 0
}
publishOut.totalTests += finalResult.totalTests;
publishOut.totalTestsSuccess += finalResult.testPassedCount;
publishOut.totalTestsFailed += finalResult.testFailedCount;
console.log(`Successfully inserted ${finalResult.insertSuccess} of ${publishOut.totalTests} test results.`);
// for (var i = 0; i < matches.length; i++) {
// var currentFile = `./testing/results/${matches[i]}`;
// fs.unlinkSync(currentFile);
// }
resolve(publishOut);
} else {
reject('Only ' + finalResult.insertSuccess + ' of ' + matches.length + ' successfully posted to the database');
}
}, function (err) {
reject('error in reduce', err);
});
I have tried several different ways of using the replaceAll with the same failure. It hits this code from the array.reduce
}, function (err) {
reject('error in reduce', err);
});
And this is the called method. The added code causing the failure in the .reduce is this Message = expectation.message.replaceAll("'", "");
protractorParser.prototype.parseResults = function (fileName) {
return new Promise((resolve, reject) => {
//console.log('In parseresults', fileName);
var currentFile = './testing/results/' + fileName
json.readFile(currentFile, function (err, obj) {
if (err != null) {
console.log('error reading file', err);
reject(err);
} else {
resolve(obj);
}
});
}).then(function (obj) {
var results = [];
for (var suite in obj) {
var specs = obj[suite].specs;
for (let i = 0; i < specs.length; i++) {
const assert = specs[i];
const tcR = /TC[\d]+/;
const tc = assert.description.match(tcR);
let Passed = 1;
let Message = '';
let Stack = '';
testResults.totalTests++;
if (assert.failedExpectations.length) {
const expectation = assert.failedExpectations[assert.failedExpectations.length - 1];
Passed = 0;
Message = expectation.message.replaceAll("'", "");
Stack = expectation.stack.split('\n')[1].trim();
testResults.testFailedCount++
} else {
testResults.testPassedCount++
}
if (tc != null) {
const time = moment().utcOffset(config.get('settings.timeOffset')).format('YYYY-MM-DDTHH:mm:ss');
const promise = utility.TestDataManager.insertAutomationResults(tc[0], assert.description, Passed, process.env.testBuild, 'P', Message, Stack, 0, time, '');
results.push(promise.then(() => {
//fs.unlinkSync(currentFile);
testResults.insertSuccess++;
//console.log('insertSuccess', testResults.insertSuccess);
},
err => { console.log('… failed', err); throw err; }
));
} else {
console.log('no test case found for test: ' + assert.description + ' -- skipping');
// I don't think you want to `throw err` here, right?
}
}
}
return Promise.all(results).then(() => testResults);
});
};
I am trying to execute an asynchronous method within a for-loop construct and then display the result. I believe the problem is that the for-loop increments before the cryto.randomBytes method calls the callback. How would I properly execute this for-loop ?
var crypto = require('crypto');
var nimble = require('nimble');
var codes = [];
nimble.series([
function(callback){
for(var i = 0; i < 100;i++){
crypto.randomBytes(64, function(ex, buf) {
if (ex) throw ex;
codes[i] = buf.toString('hex');
});
}
callback();
},
function(callback){
for(var i = 0; i < codes.length;i++){
console.log("Ticket " + i + ":" + codes[i]);
}
callback();
}]);
Yes, you are right that the loop completes before the callbacks are called. You can use an anonymous function to create a scope where each iteration gets its own copy of the variable.
Also, you would call the callback after the last value has been added to the result, not after the loop:
function(callback){
var cnt = 0;
for(var i = 0; i < 100;i++){
(function(i){
crypto.randomBytes(64, function(ex, buf) {
if (ex) throw ex;
codes[i] = buf.toString('hex');
if (++cnt == 100) {
callback();
}
});
})(i);
}
}
Instead of:
function(callback){
for(var i = 0; i < 100;i++){
crypto.randomBytes(64, function(ex, buf) {
if (ex) throw ex;
codes[i] = buf.toString('hex');
});
}
callback();
},
You might try something like:
function(callback){
for(var i = 0, len = 100; i < len; i++){
crypto.randomBytes(64, function(ex, buf) {
if (ex) throw ex;
codes.push(buf.toString('hex'));
if (codes.length === len)
callback();
});
}
},
Using an IIFE with recursivity, should work :
var crypto = require('crypto');
var nimble = require('nimble');
var codes = [];
nimble.series([
function (callback) {
// Using an IIFE
(function recursive(index) {
if (index < 100) { // i < 100
crypto.randomBytes(64, function (ex, buf) {
if (ex) throw ex;
codes[index] = buf.toString('hex');
recursive(index + 1);
});
} else callback();
})(0); // i = 0
},
function (callback) {
for (var i = 0; i < codes.length; i++) {
console.log("Ticket " + i + ":" + codes[i]);
}
callback();
}]);
I have 2 javascript requests that give back results in an array of objects.
The first object looks like this:
[Object {user_id="6", meta_value="5", user_nicename="richbai90", more...},
Object {user_id="7", meta_value="1", user_nicename="testing123", more...}]
the 2nd looks like this
[Object { usr="6", score="1 / 1", quiz_id="1"},
Object { usr="7", score="1 / 1", quiz_id="1"},
Object { usr="7", score="1/5", quiz_id="3"}]
Array 2 is the details of array one
What I need is a way to relate these together in javascript so that I can put the information from object 2 in the document where it needs to correspond with the information from object one. The easiest way I could think to do this would be to combine the arrays where the user ids were the same but this appears to be more difficult then I first thought. Here was my initial approach:
$.post(AjaxRequest.ajaxurl, {
action: "get_data"
})
.done(function (json) {
console.log(json);
var data = json;
for (var i = 0; i < json.length; i++) {
if (AjaxRequest.user_ID == json[i].user_id && json[i].Quizes == "1") {
$("#result_list").append("you have taken " + json[i].Quizes + " quiz");
} else if (AjaxRequest.user_id == json[i].user_id && json[i].Quizes != "1") {
$("#result_list").append("you have taken " + json[i].Quizes + " quizzes");
} else {
$("#result_list").append(json[i].user_nicename + " has taken " + json[i].Quizes + " quizzes" + "<br>");
}
}
getDetails(json);
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
console.log('1st Request Failed: ' + err);
});
function getDetails(data) {
$.post(AjaxRequest.ajaxurl, {
action: "get_details"
})
.done(function (details) {
console.log(data);
console.log(details);
for (var i = 0; i < data.length; i++) {
for (var i2 = 0; i2 < details.length; i++) {
while (details[i2].usr == data[i].user_id) {
console.log(details[i2]);
break;
}
}
}
$("#loading").fadeOut('fast', function () {
$("#result_list").fadeIn('fast');
});
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
console.log('2nd Request Failed: ' + err);
});
}
In this code block is where the work is happening
for (var i = 0; i < data.length; i++) {
for (var i2 = 0; i2 < details.length; i++) {
while (details[i2].usr == data[i].user_id) {
console.log(details[i2]);
break;
}
}
}
The issue is that once the while loop breaks it doesn't seem to go to the next itteration of the for loop as I would have expected instead data[i] gets undefined. If I remove the break; then data[i] is always == details[i2] and thus crashes the browser.
Maybe I'm making it harder than it needs to be?
You could try using a 2-dimensional array.