'cy.get() could not find a registered alias when using before hook

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.



Solution 1:[1]

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

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