During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId
variable within each iteration for making API queries. However, the problem lies in the fact that the variable retains its initial value of 0
and fails to update while inside the loop. Despite researching various articles on Cypress' async/sync behavior, I have not been able to find a solution.
Below is a snippet of the test:
it('Should pass', function () {
cy.visit(`${Cypress.env('appUrl')}/url`)
let questionId: number = 0
for (let index = 0; index < 9; index++) {
cy.intercept({ method: 'GET', path: `${questionId}` }).as('questionData')
cy.log('next question id: ' + questionId)
cy.intercept({ method: 'POST', path: 'answers' }).as('answers')
cy.contains('button', 'Submit answer').click()
cy.wait('@answers')
.then((xhr: any) => {
expect(xhr.response.statusCode).to.eq(200)
questionId = xhr.response.body.data.next_question_id
cy.log('new question id: ' + questionId)
cy.contains('span', 'You are correct!').should('be.visible')
cy.contains('button', 'view solution').click()
cy.contains('button', 'continue').click()
})
}
})