describe('User Login and Logout Tests with Hooks', () => {
before(() => {
// Runs once before all tests
cy.visit('https://example.com/login');
});
beforeEach(() => {
// Ensure user is logged out before each test
cy.get('body').then(($body) => {
if ($body.find('#logout-button').length) {
cy.get('#logout-button').click();
cy.url().should('include', '/login');
}
});
});
it('should log in successfully', () => {
cy.get('#username').clear().type('testuser');
cy.get('#password').clear().type('Test@1234');
cy.get('#login-button').click();
cy.url().should('eq', 'https://example.com/dashboard');
cy.get('#logout-button').should('be.visible');
});
afterEach(() => {
// Log out after each test if logged in
cy.get('body').then(($body) => {
if ($body.find('#logout-button').length) {
cy.get('#logout-button').click();
cy.url().should('include', '/login');
}
});
});
after(() => {
// Cleanup if needed after all tests
// For Cypress, usually no action needed here
});
});The before() hook runs once before all tests to open the login page.
The beforeEach() hook checks if the user is logged in by looking for the logout button. If found, it clicks logout to ensure a clean state before each test.
The test case enters username and password, clicks login, then verifies the URL and logout button visibility.
The afterEach() hook logs out the user after each test if logged in, ensuring no leftover session affects other tests.
The after() hook is included for completeness but is empty because Cypress handles cleanup automatically.
This structure keeps tests independent and reliable by managing setup and cleanup with hooks.