I am trying to set a variable to then use later on in an assert. I want to verify a date on one page is the same on another page. I have the below;
cy.get("#due > div > div > div > input").then(($dueDatePicker) => {
const dueDate = $dueDatePicker.text();
cy.log(dueDate);
});
I then have the below assert later on in the test;
cy.get("#content > div > section.content.mtm10 > div.row > div > div > div.box-body").contains(dueDate);
However Cypress tells me dueDate is undefined in the Assert.
What am I missing? Thanks
CodePudding user response:
There is a scoping issue with where you are defining the variable. There are a few ways to get around this.
The first would be to declare the variable outside of the Cypress chain.
let dueDate = ''
cy.get('foo')
.then(($el) => {
dueDate = $el.text()
})
.get('bar').contains(dueDate);
You could also return the value from the .then()
.
cy.get('foo')
.then(($el) => {
return $el.text();
})
.then((dueDate) => {
cy.get('bar').contains(dueDate);
})
I'd recommend Filip Hric's blogpost on Cypress variables for more information on understanding how the variables/scopes/timing all work together.
CodePudding user response:
As long as you are using the value later in the same test, an alias is the preferred way to store a result for a later assertion
cy.get("#due > div > div > div > input")
.invoke('text')
.as('dueDate')
...
cy.get('@dueDate').then(dueDate => {
cy.get("#content > div > section.content.mtm10 > div.row > div > div > div.box-body")
.contains(dueDate)
})