'Cypress doesn't take updated values in the repetition, only takes hard coded numbers

Why does it seems like cypress wants to know how many times the test cases will repeat before running all the test-cases. In my case I have two test files something.js and anything.js and also a cypress.env.json.

Something.js will look like this

describe('Run tests',()=>{
    let i=0
    Cypress.env('text',[])

    it('running',()=>{
         cy.get('some element').then($ele()=>{
            Cypress.env('text').push($ele.text())
         })
         i++
    })
    
    it('running',()=>{
         cy.get('some other element').then($ele()=>{
            Cypress.env('text').push($ele.text())
         })
         i++
    })
})

Now the anything.js will be dependent on the elements pushed to array Cypress.env('text') in something.js

anything.js will be like this

Cypress._.times(Cypress.env('text').length,()=>{
    describe('Run tests',()=>{
        it('run 1',()=>{
           cy.get('someting').should('exists')
           //some tests
        }) 
    
        it('run 2',()=>{
           cy.get('some other element')
           //some tests
        })
    })
 })

what the problem here is in the line Cypress._.times(Cypress.env('text').length,()=>{} Cypress.env('text').length will only be updated after something.js runs. But cypress will not show the tests written in anything.js when I run them together. It will just stop after something.js. If I give some number like 3 or 5 or anything hard coded inside Cypress._.times like this Cypress._.times(3,()=>{} and then run, cypress will run the anything.js after something.js

Can anyone tell me what this is about please and suggest me any solution?



Solution 1:[1]

The issue is that Cypress environment variables are cleared between spec files. So, when trying to do the above, your second spec file does not run because Cypress.env('text') has a length of 0 (the variable is undefined).

This example should shine a light on the behavior:

// foo.spec.js
describe('test', () => {
  it('sets the variable', () => {
    Cypress.env('foo', 'bar');
  });
});

// bar.spec.js
describe('test', () => {
  it('prints the variable', () => {
    cy.log(Cypress.env('foo'));
    // will print `undefined`, not `"bar"`.
  });
});

The clearest and most obvious solution would be to combine your two spec files into one, so that the environment variables are not cleared. However, running tests that are highly dependent on data from another test is discouraged. I would instead encourage you to find a different way to get the required data to run the second set of tests -- can you manipulate the DOM to behave in a certain way, can you set a cookie or localStorage value to change the DOM, etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 agoff