0

I can't access to variables contactName and message2Send, although they are global variables they are just working with a limited scope, how can I do to use it in other tests.

Thank you in advance!

describe('Inbox', () => { let contactName let message2Send context('Desktop viewport', () => { it('Creates a thread if none exists: necessary to all the following tests', () => { let newContact = false cy.defaultLogin() cy.get('body').then(($el) => { if ($el.find('[data-cy=inbox-empty-thread]').length > 0) { newContact = true contactName = faker.name.findName() message2Send = faker.lorem.sentence() } else { cy.get('[data-cy=inbox-thread-0]').find('[data-cy=inbox-thread-name]').then(($elem) => { contactName = $elem.text() cy.log(contactName) }) cy.get('[data-cy=inbox-thread-0]').find('[data-cy=inbox-thread-message]').then(($elem) => { message2Send = $elem.text() cy.log(message2Send) }) } }) cy.log(contactName, message2Send) cy.createThread(contactName, message2Send, newContact) }) 

1 Answer 1

2

You can do the following:

describe('Inbox', () => { let contactName let message2Send context('Desktop viewport', () => { it('Creates a thread if none exists: necessary to all the following tests', () => { let newContact = false cy.defaultLogin() cy.get('body').then(($el) => { if ($el.find('[data-cy=inbox-empty-thread]').length > 0) { newContact = true contactName = faker.name.findName() message2Send = faker.lorem.sentence() } else { cy.get('[data-cy=inbox-thread-0]').find('[data-cy=inbox-thread-name]').then(($elem) => { contactName = $elem.text() cy.log(contactName) }) cy.get('[data-cy=inbox-thread-0]').find('[data-cy=inbox-thread-message]').then(($elem) => { message2Send = $elem.text() cy.log(message2Send) }) } }) cy.then(() => { cy.log(contactName, message2Send) cy.createThread(contactName, message2Send, newContact) }) }) 

Please notice the then callback when accessing the variables. Cypress commands are asynchronous and the variables are not yet initialized when accessed without a then callback.

You can also move the assignment into a before/beforeEach hook and use the variables directly in any of your it tests

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.