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):
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);
});
});
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