I am trying to print {studentId} but unfortunately enough I can not print it.
#Get('/:studentId')
getStudentById(
#Param('studentId') studentId: string
){
console.log(studentId);
return "Get Student By Id: ${studentId}.";
}
See this => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
And this => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Related
I am trying to get a text from an element with Cypress in the first test from the first domain and then type it in the second test in another domain, here is a code
I have to grab code from h4.
I implemented next part of code:
get studentCouponValue() {
return cy.get('h4').then(($span) => {
const couponValue = $span.text();
cy.log(couponValue);
})
}
in logs, I see the correct coupon's value, but when I am trying to type it into the field I get an error
The chain approach doesn't fit my expectation, cause i am going to use it in different tests.
Try this:
get studentCouponValue() {
return cy.get('h4').then(($span) => {
const couponValue = $span.innerText;
cy.log(couponValue);
})
}
i resolved
initStudentCouponValue() {
const self = this;
return cy.get('main > .container-fluid').find('h4').then((span) => {
self.couponValue = span.text();
cy.log('First log '+ self.couponValue);
return new Cypress.Promise((resolve) => {
return resolve(self.couponValue);
});
});
}
getStudentCouponValue() {
return this.couponValue;
}
in the test where we want to use value
let couponValue;
admin.initStudentCouponValue().then(() => {
couponValue = admin.getStudentCouponValue()
});
and later we can use
coupoValue
for inputs
I am looking to iterate and print to the console the text from the text key.
For example, if this matches a string "foo bar" I am looking to print "foo bar" to the console.
var stringSearcher = require('string-search');
stringSearcher.find('This is the string to search text in', 'string' .then(function(resultArr) {
//resultArr => [ {line: 1, text: 'This is the string to search text in'} ]
});
`
In plain nodejs I would do something like this:
var source = "Hello world";
var target = "Hello";
source_arr = source.split(" ");
source_arr.forEach(function(word){
if(word.trim() === target){
console.log("target");
}
})
If all you're trying to get to is the text property of the resultArr you show, then you would do this:
console.log(resultArr[0].text)
And, in real code, you probably want to verify that the array has a .length > 0 and if there is more than one result, you might want to show all the matching results.
To iterate through all matching results:
const stringSearcher = require('string-search');
stringSearcher.find('This is the string to search text in', 'string'.then(function(resultArr) {
for (let obj of resultArr) {
console.log(obj.text);
}
});
To explain. resultArr is an array of objects. So, when you iterate the array, you get an object at each point in the array. Then, to get the text property from each object, you use obj.text.
I'd like to store initial device title, which is accessible via GUI in browser as page title, and reuse it later in the code. E.g. I want to change name of device if it is set to some particular name only, and to store an old device name in browser console log. Code might look like this:
var some_name = 'Some Name';
var title = browser.getTitle();
console.log(title);
if (title.equals('Some Name')){
some_name = 'Some Other Name';
}
setDeviceName(some_name);
unfortunately, to that protractor responds with
TypeError: title.equals is not a function
How is it possible to extract browser title as string?
Thanks.
UPDATE:
Thanks everyone, the solution due to igniteram1 is
var some_name = 'Some Name';
some_name = browser.getTitle().then(function(webpagetitle){
if (webpagetitle === 'Some Name'){
return 'Some Other Name';
}else{
return 'Some Name'
}
});
expect(some_name).toEqual('Some Other Name');
In addition to #Sudharshan Selvraj's answer,its good practice to use strict equality === instead of == and to return the value.
var some_name = 'Some Name';
some_name = browser.getTitle().then(function(webpagetitle){
if (webpagetitle === 'Some Name'){
return 'Some Other Name';
}else{
return 'Some Name';
}
});
expect(some_name).toEqual('Some Other Name');
If you aware of the new asyc/await you may use:
expect(await browser.getTitle()).toEqual("myCustomTitle");
In protractor whatever information you need from browser will be a promise and not a string. in order to fetch the value you need to resolve the promise. look at the below example.
var title = browser.getTitle();
title.then(function(webpagetitle){
if (webpagetitle == 'Some Name'){
some_name = 'Some Other Name';
}
})
.equals() is not a function in JavaScript, but it's a valid function in Java. In Java Script, we have '==', '===' as an alternative for performing equal operations.
var x=10
== compare only values of operands, not type of operands
example:
x==10 => true
x=="10" => true
=== compare both values and type of operands
example:
x===10 => true
x==="10" => false(type of x in int and "10" is string)
var someName;
browser.getTitle().then(function (webPageTitle) {
if (webPageTitle == 'Some Name'){
someName= 'Some Other Name';
}
});
I've got a simple function in protractor to get the title when in the promise it shows the title properly, but when I do console.log it gives :
Title Got is ManagedPromise::123 {[[PromiseStatus]]: "pending"}
describe('Protractor Demo App', function() {
it('should have a title', function(one) {
browser.waitForAngularEnabled(false);
browser.get('https://tasyah.com');
titleGot = browser.getTitle().then(function(promisedResult){
console.log("Title is : " + promisedResult);
return promisedResult;
})
console.log("Title Got is " + titleGot);
expect(titleGot).toEqual('Tasyah: Online Shopping For Fashion And Costume Jewellery');
console.log("Title Got is " + titleGot);
});
});
Any explanation on this is appreciated...
Thanks
Naveen
Page Object .po file
getTableRows() {
return element.all(by.css('[data-qa="qa-table"] tr'));
}
.e2e.spec file
<PROMISE-APPROCH>
obj.getTableRows().then((list)=> {
list.count().then((totalRows)=>{
expect(totalRows).toBe(10); // example
})
});
<ASYNC-AWAIT-APPROCH>
const rowsCount = await obj.getTableRows().count();
expect(rowsCount).toBe(10); // example
I recently use logstash-filter-rest, and configure it like below:
rest {
url => "http://example.com/api"
sprintf => true
method => "post"
params => {
"post_key" => "%{a_field_in_log}"
}
response_key => "my_key"
}
after this, logstash make a post request to my api, but something is wrong, the value of a_field_in_log
is identical in every request ( I check api access log, all of the value is the first field value sent to api ) it seems like there have caches for referenced field.
Does someone had encountered same problem, would thank you for your help!
As it happens, I'm the author of logstash-filter-rest and I'm glad to hear that someone is actually using it.
I was able to reproduce your issue. It was a bug and (good news) I fixed it. Thank you for reporting!
You can update now to the new version 0.1.5.
../logstash/bin/plugin update logstash-filter-rest
Test config:
input { stdin {} }
filter {
grok { match => [ "message", "Hello %{WORD:who}" ] }
rest {
url => "http://requestb.in/1f7s1sg1?test=%{who}"
method => "post"
sprintf => true
params => {
"hello" => "%{who}"
}
}
}
output { stdout{ codec => "rubydebug" } }
Test data:
Hello John
Hello Doe
Hello foo
Hello bar
Result:
http://requestb.in/1f7s1sg1?inspect (looks good)
Many thanks for contributing! I hope everything works as expected now.
When I parse this little piece of JSON:
{ "value" : 9223372036854775807 }
This is what I get:
{ hello: 9223372036854776000 }
Is there any way to parse it properly?
Not with built-in JSON.parse. You'll need to parse it manually and treat values as string (if you want to do arithmetics with them there is bignumber.js) You can use Douglas Crockford JSON.js library as a base for your parser.
EDIT2 ( 7 years after original answer ) - it might soon be possible to solve this using standard JSON api. Have a look at this TC39 proposal to add access to source string to a reviver function - https://github.com/tc39/proposal-json-parse-with-source
EDIT1: I created a package for you :)
var JSONbig = require('json-bigint');
var json = '{ "value" : 9223372036854775807, "v2": 123 }';
console.log('Input:', json);
console.log('');
console.log('node.js bult-in JSON:')
var r = JSON.parse(json);
console.log('JSON.parse(input).value : ', r.value.toString());
console.log('JSON.stringify(JSON.parse(input)):', JSON.stringify(r));
console.log('\n\nbig number JSON:');
var r1 = JSONbig.parse(json);
console.log('JSON.parse(input).value : ', r1.value.toString());
console.log('JSON.stringify(JSON.parse(input)):', JSONbig.stringify(r1));
Output:
Input: { "value" : 9223372036854775807, "v2": 123 }
node.js bult-in JSON:
JSON.parse(input).value : 9223372036854776000
JSON.stringify(JSON.parse(input)): {"value":9223372036854776000,"v2":123}
big number JSON:
JSON.parse(input).value : 9223372036854775807
JSON.stringify(JSON.parse(input)): {"value":9223372036854775807,"v2":123}
After searching something more clean - and finding only libs like jsonbigint, I just wrote my own solution. Is not the best, but it solves my problem. For those that are using Axios you can use it on transformResponse callback (this was my original problem - Axios parses the JSON and all bigInts cames wrong),
const jsonStr = `{"myBigInt":6028792033986383748, "someStr":"hello guys", "someNumber":123}`
const result = JSON.parse(jsonStr, (key, value) => {
if (typeof value === 'number' && !Number.isSafeInteger(value)) {
let strBig = jsonStr.match(new RegExp(`(?:"${key}":)(.*?)(?:,)`))[1] // get the original value using regex expression
return strBig //should be BigInt(strBig) - BigInt function is not working in this snippet
}
return value
})
console.log({
"original": JSON.parse(jsonStr),
"handled": result
})
A regular expression is difficult to get right for all cases.
Here is my attempt, but all I'm giving you is some extra test cases, not the solution. Likely you will want to replace a very specific attribute, and a more generic JSON parser (that handles separating out the properties, but leaves the numeric properties as strings) and then you can wrap that specific long number in quotes before continuing to parse into a javascript object.
let str = '{ "value" : -9223372036854775807, "value1" : "100", "strWNum": "Hi world: 42 is the answer", "arrayOfStrWNum": [":42, again.", "SOIs#1"], "arrayOfNum": [100,100,-9223372036854775807, 100, 42, 0, -1, 0.003] }'
let data = JSON.parse(str.replace(/([:][\s]*)(-?\d{1,90})([\s]*[\r\n,\}])/g, '$1"$2"$3'));
console.log(BigInt(data.value).toString());
console.log(data);
you can use this code for change big numbers to strings and later use BigInt(data.value)
let str = '{ "value" : -9223372036854775807, "value1" : "100" }'
let data = JSON.parse(str.replace(/([^"^\d])(-?\d{1,90})([^"^\d])/g, '$1"$2"$3'));
console.log(BigInt(data.value).toString());
console.log(data);