Reputation: 313
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)
})
Upvotes: 0
Views: 377
Reputation: 1112
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
Upvotes: 2