Karate.callSingle() function returns [object Object] [duplicate] - cucumber

This question already has an answer here:
setting global config values in karate
(1 answer)
Closed 1 year ago.
Trying to pass git credntials from config.params to download testdata from git once before everything to used all the features files(testing).
I used karate.callSingle() function exeute to repo.feature along with argument.
Below is karate-config.js file.
var config={
URL : "http://api.com",
params : {"password":pws, "username":user }
}
if( Catg == "_model"){
var getGit = karate.callSingle('classpath:com/repo.feature', config.params);
var gitrepo= getGit
}
In repo.feature trying to get value of params. Tried lots of ways BUT getting below errors.
* print '#{config.params}'
// it returns -- #{config.params}
* def code1 = __arg.params
* print code1
// it returns -- null
* print params
// it returns error -- params is define
* print config.params
// it returns error -- config is define
Tried to print values in karate-config.js file, then it returns [object Object]
karate.log("******"+ config.params+" ----------")

If * print params does not work, you must have missed something basic. Please follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

Related

await import in React/NextJS/Typescript [duplicate]

This question already has answers here:
useRouter/withRouter receive undefined on query in first render
(9 answers)
Closed 3 months ago.
I'm running this code on a node.js development server:
import { useRouter } from 'next/router'
import nextBase64 from 'next-base64';
const Load = () => {
const router = useRouter()
const { obj } = router.query
var decoded = nextBase64.decode(obj)
return <p>Post: {decoded}</p>
}
export default Load
When I navigate to the page, which is a base64 encoded string, It tells me:
Server Error
TypeError: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
pages/media/load/[obj].tsx (15:16) # Load
13 | const router = useRouter()
14 | const { obj } = router.query
> 15 | var decoded = nextBase64.decode(obj)
| ^
16 |
17 | return <p>Post: {decoded}</p>
18 | }
However, if I remove the nextBase64.decode(obj) and print the obj it works, printing the encoded string. But here's the kicker. When I revert the change it also works and prints the decoded string.
I think the import nextBase64 from 'next-base64'; statement isn't imported in time for when the function is exported.
What is best practice here, should I do some kind of await import (I tried and failed) or should I import inside the function somehow?
this is the normal behavior of router.query if you're not using getServerSideProps or getStaticProps. or you can use router.isReady inside of useEffect.
see the below codesandbox example

How to use environment variable in Typescript properly? [duplicate]

This question already has answers here:
using process.env in TypeScript
(19 answers)
Closed 1 year ago.
I'm trying to make a simple api using typescript and when I use any env variable I get an error from TS compiler Tells me that this could be undefined
example
// Not Working
const db = process.env.DB_URL // This gives an error that the result could be a string or undefined
to fix this
I have to make a type guard and check with if statement as follows
const db = process.env.DB_URL
if (db){
// ....
}
Is there a better approach to to such a thing instead of explicitly check for every variable ?
You can apply null check and keep it as string instead of defining two types:
const db: string = process.env.DB_URL ?? ''
// empty strings are falsy/falsey
if (db) { // do this}
else { //do this}

NodeJS readFileSync and Regex the resulting text [duplicate]

This question already has answers here:
How to use JavaScript regex over multiple lines?
(8 answers)
Closed 4 years ago.
Looking to scrape the comments out of a JS file. Was thinking I can create a function to input a .js file, perform a RegExp match, and output an array of strings using fs.readFile() and string.match();
Here's an over-simplified example:
I have two files class.js (to read) and parse.js (to perform the text parsing)
class.js:
/*
by: Mike Freudiger
*/
/**
* one
* #returns 'Hello World'
*/
function one () {
return 'Hello World';
}
alert();
/* end of file */
parse.js:
var fs = require('fs');
var file = fs.readFile('C:\\Users\\mikef\\Desktop\\node_regex_test\\class.js', 'utf8', function(err, doc) {
var comments = doc.match(/(\/\*\*(.|\n)+?\*\/)/g);
console.log(comments);
});
when I run node parse.js the console output is null.
However when I run the regex match on a multiline string, I get the expected output:
var doc = `/*
by: Mike Freudiger
*/
/**
* one
* #returns 'Hello World'
*/
function one () {
return 'Hello World';
}
alert();
/* end of file */`
Any idea why the readFile() string would behave differently than a string literal?
...Also, I realize there may be a better way to get these comments out, with another npm package or something, but now I really just want to know why these two strings are different.
As mentioned by vsemozhetbyt, it seems that newlines used in class.js file are either \r\n or \r.
One of the simplest (and fastest) way to match these newlines would be to use [\s\S] instead of (.|\n) in your regex.
Thus you get:
var fs = require('fs');
var file = fs.readFile('C:\\Users\\mikef\\Desktop\\node_regex_test\\class.js', 'utf8', function(err, doc) {
var comments = doc.match(/(\/\*\*[\s\S]+?\*\/)/g);
console.log(comments);
});

Null Commond line argument

I am passing around 9 parameter via command line to Node JS script.
Here is my Command:
node awsInvokeDelete.js DELETE https://Test1234.execute-api.us-west-2.amazonaws.com us-west-2 /qa/transit-connectivity/api/v1/sites/tdcloudtsttd03 AKIAJ4Y5DGqwewqeqw CFdAgsdtqweqwe/SKqDezdqweewofWrUXXBbQoMy '{\"change_request\":\"chg0123456\"}'
I am passing query parameter as JSON in command line argument which is process.argv[9] in node JS script. It works perfectly If I pass value to all parameters but in some cases process.argv[8] will be empty. When I am passing empty value in process.argv[8], its actually takes argv[9] as argv[8].
how Can I pass empty argument value in command line for below script.
var apigClientFactory = require('aws-api-gateway-client').default;
let awsMethod = process.argv[2],
awsEndpoint = process.argv[3],
awsRegion = process.argv[4],
awsPathTemplate = process.argv[5],
awsAccessKey = process.argv[6],
awsSecreteKey = process.argv[7],
awsPathParams = process.argv[8],
awsAdditionalParams = JSON.parse(process.argv[9] || '{}');
var apigClient = apigClientFactory.newClient({
invokeUrl: awsEndpoint, // REQUIRED
accessKey: awsAccessKey, // REQUIRED
secretKey: awsSecreteKey, // REQUIRED
region: awsRegion, // REQUIRED: The region where the API is deployed.
retryCondition: (err) => { // OPTIONAL: Callback to further control if
request should be retried. Uses axon-retry plugin.
return err.response && err.response.status === 500;
}
});
var param = awsPathParams;
// Template syntax follows url-template https://www.npmjs.com/package/url-template
var pathTemplate = awsPathTemplate;
var method = awsMethod;
var additionalParams = { queryParams: awsAdditionalParams, };
console.log(additionalParams);
var body = {};
apigClient.invokeApi(param, pathTemplate, method, additionalParams, body)
.then(function(result) {
//console.log(result.data + ": " +result)
console.log(result.response.data)
}).catch(function(result) {
console.log(result.response.data)
});
Here is output: args[8]'s value should be displayed as args[9]
args[8]: {"change_request":"chg0123456"}
args[9]: [object Object]
Your script is not working on the input that you have provided (if you actually add the missing argument) because '{\"change_request\":\"chg0123456\"}' is not something that JS can parse as a JSON string. Furthermore, you are not passing any empty value in your input to the script (just an empty space is not considered as an actual input).
You need to change it to this '{"change_request":"chg0123456"}' and pass empty value as an empty string ''.
This input works correctly.
node index.js DELETE https://Test1234.execute-api.us-west-2.amazonaws.com us-west-2 /qa/transit-connectivity/api/v1/sites/tdcloudtsttd03 AKIAJ4Y5DGqwewqeqw CFdAgsdtqweqwe/SKqDezdqweewofWrUXXBbQoMy '' '{"change_request":"chg0123456"}'
If you really need the object in that format, then you need to remove \ characters from it before you can call JSON.parse on it.
awsAdditionalParams = JSON.parse(
process.argv[9].split('\\').join('') || '{}'
);
If you first want to check whether the last argument is not empty and only then run the code above, the you can use ternary operator like this.
awsAdditionalParams = process.argv[9]
? JSON.parse(process.argv[9].split('\\').join('') || '{}')
: '';
3 options:
change the script to switch around arguments 8 and 9. then you always have the same number even if 9 is empty.
pass the argument as "" instead of nothing.
change the script so you parse your own command line and change things around whichever way you like.

Logging variable in nodejs

I have a variable named, 'res'. This variable if used with console.log() print all request to a function. My question is... How to log this variable in a log.txt file?
Example using console.log(res)
Print in console:
[ 'AndroidShareANE',
'pixi.js',
'ShortSword',
'faceshiftparser',
'clmutils',
'chaikin-smooth',
'getuservideo',
'getboundingbox',
'clmdraw',
'SpriteSheetScrubberTutorial',
'interpolation-arrays',
This is a one part of response.
My purpose is log in log.txt file the var content. Identical to console.log() result.
Thanks for your collaboration, and sorry my bad english.
The easiest way is to create a new Console object that writes to your file. The docs have an example of this exact thing, which I'll reproduce here for posterity:
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
var count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5
If you don't pass the second argument (errorOutput) to new Console then the error output will also be written to the output file.

Resources