I'm searching a way to get back a return value returned by a custom Cypress commands.
I'm currently using Cypress and Cypress-promise lib (https://www.npmjs.com/package/cypress-promise)
Currently, result is that: log1=CAR 1 log2=null
Where is my mistake ?
Test file:
it('Test 1', async function() { const carName = await promisify(cy.set_typeCarName()); cy.log("log2 = " + carName ); });
module:
set_typeCarName() { let carName = "CAR 1"; cy.get('#newSiteCityInput').type(carName); cy.log("log1 = " + carName); return carName; }; Cypress.Commands.add('set_typeCarName',() => { webnewsite.set_typeCarName(); });
Cypress commands are not complete Promises, as they can't run in parallel and can't have explicit exception handling with ".
If you would like to test/assert the value of an input element, just use . should('have. value', 'input value you test for') .
Cypress custom commands are described by users and not the default commands from Cypress. These customized commands are used to create the test steps that are repeated in an automation flow. We can add and overwrite an already pre-existing command. They should be placed in the commands.
To do this I'm using wrap()
to return a Chainable
containing the value I want to return.
Module
function foo() { return cy.wrap('foo'); } Cypress.Commands.add('foo', foo);
Test File
cy.foo().then(value => console.log(value)); // foo
Since wrap()
is returning a Cypress.Chainable
, we can call .then()
on our commands. What ever is passed into wrap()
is yielded to the next command.
See also: Cypress wrap() documentation
Cypress introduces a new way of writing code instead of returning values, i.e. using alias. https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Closures
Normal way of writing code
async function compute(){ const value = await (asynchronous function); return value; } const x = await compute(); // #a console.log(x); // #b
How to do this is in Cypress, since we cannot use async/await in cypress
function() compute{ cy.get('p#text').then(p => { const text = p.textContent; cy.wrap(text).as('pText'); //even if we return text from here, it will not be accessible anywhere }); } compute(); // #a cy.get('@pText').then(text => { console.log(text); // #b }
The crux is to alias the value and then use it in the next command
because
Cypress first runs through whole code and puts commands in queue
once code is in queue, next command in queue will only run after all callbacks of current command are completed, thus we can use above code pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With