How to get response from cy.exec() - cypress

I am having hard time trying to get response from cy.exec() call.
For example:
cy.exec("java -version").then((response) => {
cy.log("response is " + response);
});
The output I have is looking like this:
log response is [object Object]
What do I do wrong here?

cy.exec() yields an object with the following properties:
code
stdout
stderr
So to get the java version you have to log the stderr property
cy.exec("java -version").then((result) => {
cy.log(result.stderr);
})
Test Runner Screenshot showing Java version:

In the docs
cy.exec() yields an object with the following properties:
code
stdout
stderr
So for your particular execution string, the response is probably on stdout
cy.exec("java -version").then((response) => {
cy.log("response is " + response.stdout);
})

Related

cy.url().should() failing with type error

We have the following piece of code that fails intermittently.
cy.url().then((url) => {
if (url.includes('https://app') || url.includes('https://auth')) {
cy.url().should('match', /\/agent|\/worker/, { timeout: 30000 }) ^
}
})
The failure happens in the second cy.url() command where the should match condition fails with the error "[object Object]: expected undefined to match". We only see this error every once or so in 10 time.
Instead of again using cy.url(), use the previous url you extracted with cy.wrap(), something like this:
cy.url().then((url) => {
if (url.includes('https://app') || url.includes('https://auth')) {
cy.wrap(url).should('match', /\/agent|\/worker/, {timeout: 30000})
}
})
I'm not sure of the reason for covering multiple scenarios like this would be.
Also, you don't give an example of the url, I'm going to assume your regex is to check the pathname of the url.
cy.location('pathname').should('match', /\/agent|\/worker/i)

Can Cypress give me an error message when there has been an error?

I have the below snippet from my test case:
cy.get('item_here').should('not.exist');
Can cypress give me a custom error message when the "item_here" does exist?
Thanks,
You can chain a log message on to the existing code, and it will only run if the element does not exist.
cy.get('item_here').should('not.exist')
.then(() => cy.log('no such element found')) // Note; this is an additional log
Changing both "success" and "fail" messages is hard because Cypress likes to show the red AssertionError block when anything fails or an error is thrown.
You can use the should() callback version, but please use an expect() inside otherwise you do not have retry,
cy.get('item_here').should($el => {
expect($el, 'Cannot be found').to.not.exist // expect causes retry for 4 seconds
Cypress.log({
name: 'Missing',
message: 'Cannot be found'
})
})
You can throw your own errors in a callback function for .should().
cy.get(".does-not-exist")
.should("not.exist")
.then(($el) => {
if ($el == null) {
throw new Error("Item does not exist in DOM");
}
});

In my Cypress.io tests why do I need to treat a cy.task like it is asyncronous when its not

I have Cypress.io tests that use a simple Cypress task to log some table information to the terminal. For example I have a test like so:
it("Writes some console logs and checks a val", () => {
cy.task("rowLog", { id: 1, name: "foo", type: "bar" });
let one = 1;
expect(one).to.equal(2);
});
And the task, "rowLog" like so:
module.exports = (on, config) => {
on("task", {
rowLog(data) {
// use node.js console.table to pretty print table data:
console.table(data);
return null;
},
}
But the result of rowLog will not display in my terminal if I run Cypress headlessly via Cypress run. This is because the test will fail. If we switch the test so that it passes, then it will show.
However I just realized that if I treat rowLog like it's async like below. It will print the results to the terminal:
it("Writes some console logs and checks a val", () => {
// add a .then to task:
cy.task("rowLog", { id: 1, name: "foo", type: "bar" }).then(() => {
let one = 1;
expect(one).to.equal(2);
});
});
This is not what I would expect from the docs. They say that:
cy.task() yields the value returned or resolved by the task event in the pluginsFile.
(source)
And that a task can yield either a promise or a value.
I'm new to Cypress here-- is there something I'm missing or doing wrong? I'd like to be able to not have to chain my tasks with .then statements if it is just synchronous stuff like writing output to ensure everything is emitted to my terminal.
If you look into the type definition of cy.task command, you will see that it returns a Chainable (that is a promise-like entity). So it behaves like any other cy command (ansynchrounously).
As for the yield either a promise or a **value** - this statement refers to the handler of the task, not the task itself. As for the other command, Cypress will wrap a returned value into a promise if it was not done by the handler.

Handling errors using Parse.com Cloud Code and javascript API

What is the best way to handle errors using Parse.com Cloud Code. I'm able to use console.log and Firebug to see when Parse Cloud Code throws an error, but I need some help with how to notify the client that something went wrong. Some sample code from both sides would really be great -- Cloud Code and client side javascript code.
I preferred it this way -
On Cloud Code make one ErrorHandler.JS file -
exports.sendError = function(response, message, data) {
console.log("Message - " + message + " Data - " + JSON.stringify(data)); // To print LOG on Cloud Code
// Moreover you can use any of - "console.error/warn" - as mentioned - https://parse.com/docs/cloud_code_guide#logging
response.error({
status : false, // Indicates EXECUTION STATUS - I am using "successHandler" also & using STATUS as "true"
message : message, // Refers to Error Message
data : data || {} // Error Object or your customized Object
});
}
& client side you will have all data to print if you want or you can just show alert message to the Users.
More over it's preferred to check both SERVER side as well as CLIENT side LOG for DEVELOPING purpose because PARSE Cloud Code stores only last 100 messages in LOG.
& In order to implement proper LOGGING you must made some custom procedures with proper storage structure in terms of CLASS.
Parse has a section on Error Handling for Promises.
For instance when running a query in Cloud Code
query.find().then(function(result){ ... },
function(error){
response.error("Error occurred: " + error.message);
}
That will send error message down the client.
As an experiment I tried response.error with various strings/objects, below is what each returned (the commment shows the return value to the client).
Essentially, it always returns code 141, and you can only return a string. I was surprised that passing the proverbial err object from an exception returned {} my guess is this is for security reasons. What I do not understand is why you can't console.log(err) on the server as this has caused me a lot of confusion when trying to figure out what is going on. You basically always need to do err.message in your console.log statements to figure out what's really going on.
response.error("Some String of text") // --> {code: 141, message: "Some String of text"}
response.error( new Error("My Msg") ) // --> {code: 141, message: "{}"}
try {
var x = asdf.blah;
}catch(err) {
return response.error(err.message); // --> {code: 141, message: "asdf is not defined"}
}
response.error( err ); // --> {code: 141, message: "{}"}
response.error( Parse.Error(Parse.Error.VALIDATION_ERROR, "My Text") ); // --> {code: 141, message: "An error has occurred"}

log stack trace when HTTP request return error in Jmeter

I want to log all error message for failed HTTP request. I am going to run the thread group for 1B users and I don't want to use the View Result Tree because it logs everything and log file will bloat.
Currently I am using Beanshell Assertion as below.
if (Boolean.valueOf(vars.get("DEBUG"))) {
if (ResponseCode.equals("200") == false) {
log.info(SampleResult.getResponseMessage());
log.info("There was some problem");
}
}
But in this case it just prints the error message but I am interested to log the stack trace returned by the server.
I also used this method as mention in this thread
for (a: SampleResult.getAssertionResults()) {
if (a.isError() || a.isFailure()) {
log.error(Thread.currentThread().getName()+": "+SampleLabel+": Assertion failed for response: " + new String((byte[]) ResponseData));
}
}
But in this case I don't get an object out of SampleResult.getAssertionResults() method and it doesn't display anything in case of HTTP request failure.
Any idea how to get the stacK trace?
I figured it out. SampleResult has one more method called getResponseDataAsString(). This method returns the response message. In case of error it contains the error message.

Resources