'Cypress: Code in page object file is being executed as a test case before the before hook

I was trying to use a condition as a function within a page object.

class Folders {

    DropdownCheckFunction(){   
        cy.get('.more-less-container').then((dropdown) => {
        if(dropdown.find('.name').contains('More')){
            cy.get('more-less-container').click()
        }
        else{
            console.log('folders are in expanded state')
        }
    })

}    

    Drafts(){
        this.DropdownCheckFunction()
        cy.get('.category-content').find('[title="Drafts"]').click()
          .get(".folder-details").should('contain.text', 'Drafts')
    }

Issue here is that the page object is getting executed as a test case and is happening before the code in BEFORE hook is being run. Below is the test file code

describe('Testing all cases related to Drafts', () => {
    
    before(() => {
        cy.login()
      })
    })


it('Needs to open the Drafts folder', () => {
        openFolder.Drafts()
    });

Attaching the error seen on the test runner for reference

Image showing the Error on the test runner



Solution 1:[1]

The problem is bad formatting.

If you line up your code, you can see it - your test is outside the scope of the before().

describe('Testing all cases related to Drafts', () => {
  before(() => {
    cy.login()
  })
})         // move this bracket to below the `it()`


it ('Needs to open the Drafts folder', () => {
  openFolder.Drafts()
});

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 Fody