cypress: get inputs by name with variable - get

const dates = {
street: "Bauweg",
house_number: "22",
post_code: "22222"
}
describe("test legal-new site", () => {
it("test for typing in input boxes", () => {
for (let date in dates) {
console.log(date)
cy.get("input[name=date]")
.focus()
.clear()
.type(dates[date])
.blur()
}
})
})
Error-Message from cypress:
Expected to find element: input[name=date], but never found it.
I wrote the date with backticks, but is not correct too. I checked with console.log(date): all o.k. All keys from dates are showed.
What is wrong in this element? I think it s a format problem with date, but I don't know where I can find a solution.

You have a couple of options
from string concatenation
for (let date in dates) {
const selector = "input[name=" + date + "]"
cy.get(selector)
...
}
from template literal
for (let date in dates) {
const selector = `input[name=${date}]`
cy.get(selector)
...
}

There are a few things incorrect with your implementation.
const dates = {
street: "Bauweg",
house_number: "22",
post_code: "22222"
}
describe("test legal-new site", () => {
it("test for typing in input boxes", () => {
// use lodash forEach to access the key values since dates is an object
Cypress._.forEach(dates, function(value, key){
console.log(date)
// use template literal here `string${variable}`
cy.get(`input[name=${key}]`)
.focus()
.clear()
.type(value)
.blur()
}
})
})

Related

NodeJS Replace all values of a defined key in a json file

im trying to go from this:
{
"Level":"A",
"Group LVL2":{
"Level":"B",
"Group LVL3":{
"Level":"C"
}}}
To This
{
"Level":"C",
"Group LVL2":{
"Level":"C",
"Group LVL3":{
"Level":"C"
}}}
So i basically want to replace all values of a json key to be the same.
This a part of the code im using:
const fs = require('fs');
const fileName = './' + (Profile) + ".json";
const file = require(fileName);
const key = (Root);
file[Root] = (Value);
fs.writeFile(fileName, JSON.stringify(file, null, 2), function writeJSON(error) {
if (error) return console.log(error);
But it only replaces the Level Value of the first json group/line:
{
"Level":"THIS WILL BE REPLACED",
"Group LVL2":{
"Level":"THIS WILL NOT BE REPLACED",
"Group LVL3":{
"Level":"THIS WILL NOT BE REPLACED"
}
}
}
Hope i can find a solution to this, i count on you!
(There doesn't seem to be any beginner friendly solution online)
Below is the general solution for this kind of problem, maybe you can make it more efficient depending on your problem.
It loops through all keys of the object that are nested objects themselves, recurses for each object in the json and updates the "Level" key.
function replaceValues(obj) {
if(obj.hasOwnProperty(key))
obj[key] = value;
for (let property of Object.keys(obj)) {
if (typeof(obj[property]) === "object") {
replaceValues(obj[property]);
}
}
}
Tested on the data you provided with Value = "D"
{
"Level": "D",
"Group LVL2": {
"Level": "D",
"Group LVL3": {
"Level": "D"
}
}
}

how to scrape data from a website using node

I am new in Node JS. from morning i am trying to scrape data from website https://www.pmkisan.gov.in/StateDist_Beneficiery.aspx
[![enter image description here][1]][1]
I want to store that date also in db table. Currently i am putting hard coded date. But how can i scrape that date?
my code
(async () => {
await performDbActions(webData);
})();
async function performDbActions(data) {
let dataToBeInsert = {};
// console.log(data);
for (const d of data) {
if (Object.keys(d).length) {
// console.log(d);
let district = await db.sequelize.query("select * from abc where name=:districtName or other_names like :districtLike", {
replacements: {districtName: d['name'], districtLike: '%' + d['name'] + '%'},
raw: true,
type: db.sequelize.QueryTypes.SELECT
});
delete d['sno'];
delete d['name'];
d['as_on'] = '2020-02-06';
}
}
}
}
According to the page's source code the date you're looking for is inside a <span> that has the id ContentPlaceHolder1_lbldate. So you can just use cheerio to get its text-content and pass the result to performDbActions as an additional parameter:
//...
const date = $('#ContentPlaceHolder1_lbldate').text();
//...
await performDbActions(webData, date);
// ...
async function performDbActions(data, date) {
// ...
// it would be safer to use an external date-library like moment.js but here's a way to convert the date in plain js
const dateParts =date.split('/');
const dateObj = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
d['created_at'] = dateObj;
}
Note that the date is in format dd/mm/yyyy, so you may have to convert it to your desired format.

node js access value in json result and get the value

i have following json object which i get from API end point
let myjson = { Team1: { SCORE: 10 } }
i want to access the score inside Team but not able to complete as i need to just the result as 10
i have tried following code but not able to get the result
for(var attribute name in JSON.parse(myjson)){
return console.log(attributename+": "+body[attributename]);
}
i also used bellow code
const userStr = JSON.stringify(myjson);
JSON.parse(userStr, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
Not a node developer but why do you need to json.stringify it? Can't you just reach the value with dot notation like this:
myJson.Team1.SCORE
myjson is already an Object, you don't need to do JSON.parse nor JSON.stringify on it.
Just access the property directly:
console.log(myjson.Team1.SCORE)
If you have multiple teams, or want to access it dynamically:
const obj = { Team1: { SCORE: 10 }, Team2: { SCORE: 20 } }
for(const [team, value] of Object.entries(obj)) {
console.log(`${team}: ${value.SCORE}`)
}
you also can use this if it fulfills your query.
here is the code.
let myjson = {Team1: {SCORE:10}, Team2: {SCORE: 20}};
Object.keys(myjson).forEach(function(item) {
console.log(myjson[item].SCORE);
});
Not sure if there can be more teams in that object, so I put here some more complex solution and then the straightforward one.
const myjson = { Team1: { SCORE: 10 }, Team2: { SCORE: 20 } }
const result = Object.keys(myjson).map(key => myjson[key].SCORE);
console.log('For dynamic resolution', result);
console.log('If there is only Team1', myjson.Team1.SCORE);

Dynamically change elasticsearch query definition

So I am trying to dynamically delete specific documents from elastic and would like to use one function without hard coding the name of the item I am looking for the time range in. See code below:
exports.cleanElastic = function(type, timeReference){
return new Promise (function (resolve, reject){
let dataOlderThan = "now-".concat(config.amountOfData);
elastic.deleteByQuery({
index: 'canary',
type: type,
body: {
query: {
range : {
START_TS: {
lte: dataOlderThan
}
}
}
}
},
As you can see 'START_TS' is the name of the date field I care about in this instance. That will not always be the case with the project. So I am trying to pass 'timeReference' or at least its' value in for where the query reads 'START_TS'. Any suggestions would be much appreciated.
Thank you,
Ryan
I think what you are asking is more of javascript to convert strings to symbols.
exports.cleanElastic = function(type, timeReference){
return new Promise (function (resolve, reject){
let dataOlderThan = "now-".concat(config.amountOfData);
elastic.deleteByQuery({
index: 'canary',
type: type,
body: {
query: {
range : {
toSymbol(timeReference): {
lte: dataOlderThan
}
}
}
}
}
}
}
function toSymbol(variable) {
return Symbol(variable);
};
In rails we use something like following for this.
key_name = 'age'
hash = {
name: 'john',
key_name.to_sym => '23'
}

Sails.js find() date

The following queries return an empty array although my database has records in the given date.
Event.find({date: "2016-12-25"}).exec((err, holidays) => {
console.log(holidays);
}
let myDate = new Date(parameters.year,parameters.month,parameters.day);
Event.find({date: myDate}).exec((err, holidays) => {
console.log(holidays);
}
Anything I'm missing?
According to the documentation you could do it like so:
Model.find({ date: { '=': new Date('2/7/2014') } })

Resources