score:2

Accepted answer

setting a global variable quite often will not work, because of the asynchronous nature of a web app. the docs refer to this as doing a backflip.

the most reliable way to handle this is either with a closure or with an alias.

closures

to access what each cypress command yields you use .then().

cy.get(".muitablebody-root").find("tr").its('length').then(intiallength => {

  // code that uses initiallength is nested inside `.then()`

  cy.get("#addrowbutton").click();
  cy.get(".muitablebody-root").find("tr").should("have.length", intiallength + 1);

})

aliases

allows you to separate the code that creates the variable from the code that uses it.

cy.get(".muitablebody-root").find("tr").its('length').as('intiallength');

cy.get("#addrowbutton").click();

// other test code

cy.get('@intiallength').then(intiallength => {
  cy.get(".muitablebody-root").find("tr").should("have.length", intiallength + 1);
})

why not a global variable?

using a global variable is anti-pattern because it often creates a race condition between the test code and the queued commands.

by luck, your example will work most times because cy.get("#addrowbutton").click() is a slow operation.

but if you want to test that the row count has not changed, then using a global variable will fail.

try this

var intiallength = 0;
cy.get('table').find("tr").then((tr) => {
  intiallength = tr.length;
})

// test that row count remains the same
cy.get('table').find("tr").should("have.length", intiallength);  
// fails because it runs before the variable is set

this is because the test code runs much faster than the .get() and .find() commands, which must access the dom.

although the above example is trivial, remember that web apps are inherently asynchronous and backflip tests can easily fail.

score:0

with find() you can do something like:

var tablelen = 0;
cy.get(".muitablebody-root").find("tr").then((tr) => {
    tablelen = tr.length,
})

and then:

cy.get("#addrowbutton").click(); //new tr inserted
cy.get(".muitablebody-root").find("tr").should("have.length", tablelen + 1);

Related Query

More Query from same tag