Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a variable's value from a test to the next one in Cypress

Is it possible to pass a variable from one it test to the next it test ? The following using cy.wrap does not work:

it('test1', () => {
 const var1 = 'test'
 cy.wrap(var1).as('var1Alias')
})
it('test2', () => {
 cy.get('@var1Alias').then(var1Alias => {
    // do stuff with the var1Alias
  })
})

I've checked old stackoverflow questions similar to mine such as this: Use variables across multiple 'it' statements to track change in Cypress and the difference is that the variable is declared globally outside the tests (it). Hence, you can always replace the variable.

My specific issue is that the dependency on the variable's value from the previous test. I know Cypress best practice suggests that tests shouldn't be sequential but this is a common scenario in my opinion to properly categorise tests in a readable manner.

For context, my first test is calling a POST endpoint then the response body will be passed as a query parameter for my GET endpoint in the succeeding test.

Current workarounds (while I am still looking for a better option):

  • Use fixtures and write then retrieve (slower runtime)
  • Use localstorage-commands plugin (I have multiple variables to retrieve)
  • Include the succeeding test inside the arrow function of the previous test (thus combination both tests in one test)
like image 278
ebanster Avatar asked Sep 05 '25 15:09

ebanster


1 Answers

If your it() tests share the same domain, you should use traditional function declaration "function() {do smth}" so you can use this. context, just right after the describe() define let variable with no value. After that in .then() inside your test "it()" you can redefine variable value like this.str = value; This value will be saved and can be passed to other it();

Example:

describe('test', function() {
  let str;
  it('take value from input', () => {
    cy.visit('/');

    cy.contains('Forms').click();
    cy.contains('Form Layouts').click();
    cy.contains('nb-card', 'Using the Grid').find('[data-cy="imputEmail1"]').type('[email protected]').invoke('val').then((value) => {
      this.str = value;
    });
  });

  it('put value', () => {
    cy.visit('/');
    cy.log(this.str);
  });
});
like image 91
Yurii Ya Avatar answered Sep 08 '25 11:09

Yurii Ya