describe("Share Link", () => {
beforeEach(() => {
cy.generateLink().then(response => {
let url = response.meeting_shared_link.split("/");
cy.wrap(url[url.length - 1]).as("link");
});
describe("when I turn on link sharing", () => {
// This works. Changing it to a before hook breaks it.
beforeEach(() => {
cy.get("@link").then(link =>
cy.toggleLinkSharing({ link: link })
);
});
});
I am currently generating an alias - @link - in my first beforeEach hook, and then accessing it in the next beforeEach hook which is nested in a describe.
My problem is that I need the latter hook to be a before, rather than a beforeEach.
When I modify it to a before hook - it is unable to find the alias "link". Why?
I understand that aliases are cleared between each test, hence the need for the first beforeEach hook - but why isn't it available inside a before hook?
Edit:. I think, it may be because the latter defined before hook triggers before the first beforeEach - in which case, the alias didn't yet exist. If this is the case - it's not intuitive. The before hook should only fire after the beforeEach since it's nested in another describe.
You can change the outer beforeEach() to before(), and preserve the alias between tests with beforeEach(function() { cy.wrap(this.link).as('link') })
It works because this.link is not cleared between tests, even though the alias @link is cleared.
describe("Share Link", () => {
before(() => {
cy.wrap('my-url').as("link");
console.log('Outer before')
});
describe("when I turn on link sharing", () => {
beforeEach(function() { cy.wrap(this.link).as('link') }) // preserve the alias
before(() => {
cy.get("@link").then(link => {
console.log('Inner before', link)
})
})
it('1st test', () => {
cy.get('@link').then(link => console.log('1st test', link))
})
it('2nd test', () => {
cy.get('@link').then(link => console.log('2nd test', link))
})
})
})
Console output
Outer beforeEach
Inner before my-url
1st test my-url
2nd test my-url
You can use this.link and try out.
describe("Share Link", () => {
beforeEach(() => {
cy.generateLink().then(response => {
let url = response.meeting_shared_link.split("/");
cy.wrap(url[url.length - 1]).as("link");
});
describe("when I turn on link sharing", () => {
// This works. Changing it to a before hook breaks it.
beforeEach(() => {
cy.toggleLinkSharing(this.link)
});
});
Reference here: https://docs.cypress.io/guides/core-concepts/variables-and-aliases#Sharing-Context