I have a problem in a cypress the test run basing on JavaScript.
If I run the following test probably the arrays and / or global variable / array do not work.
In the browser test step log it says "wrap null". So I assume the values and arrays are empty. Is that so?
// Global variable for later use
let globalValues;
describe('Test a specific page', () => {
it('Check a specific table', () => {
let valuesArray = [];
// Run through the table row and save values in an array
cy.get('.table1 > tbody > tr.table_class3 > td:nth-child(1)').each(($e1, index, $list) => {
var titletext = $e1.text()
if (titletext.includes('Amount Summery')) {
let values = [];
// Run through the columns 2 to 15
for (let i = 2; i <= 15; i++) {
cy.get(`.table1 > tbody > tr.table_class3 > td:nth-child(${i})`).eq(index).then(function (amount) {
values.push(amount.text().trim());
});
}
valuesArray.push(values);
}
});
// Wait until all values are read and save them into the global variable
cy.wrap(null).should(() => {
globalValues = valuesArray;
});
// The global variable is ready to use for other tasks in the test
})
})
Maybe this part is synchron?
cy.wrap(null).should(() => {
globalValues = valuesArray;
});
If I do something like this for asynchronous reasons:
cy.get('#anHTMLelement').then(function(wrapfunction){
cy.wrap(null).should(() => {
globalValues = valuesArray;
});
})
This does not work neither.
I do not find the error. Any idea?
2
Answers
Change
wrap()
tothen()
, but you may have to use the value inside thethen()
depending on what your "other tasks" are.Other option to avoid putting all other tasks in
.then()
, gather the data inbefore()
orbeforeEach()
.This works because Mocha
before()
andit()
blocks complete all commands before running the next block.You can find out general concepts about global values from this page Variables and Aliases
You can change your
cy.wrap().should()
line to assert the data is presentbut as @rubio says that only ensures the data is present inside command callbacks, not at the test context level, for example
HTML Table
Test failing at test context usage of globalValues
Using jQuery to extract data in the test context
If the page is fully loaded, you can use jQuery equivalent to Cypress commands: