/// <reference types="cypress" />
// cypress/support/pageObjects/LoginPage.js
class LoginPage {
visit() {
cy.visit('https://example.com/login');
}
fillUsername(username) {
cy.get('#username').clear().type(username);
}
fillPassword(password) {
cy.get('#password').clear().type(password);
}
clickLogin() {
cy.get('button[type="submit"]').click();
}
}
export default LoginPage;
// cypress/integration/login_spec.js
import LoginPage from '../support/pageObjects/LoginPage';
describe('Login Test using Page Object Model', () => {
const loginPage = new LoginPage();
it('should login successfully with valid credentials', () => {
loginPage.visit();
loginPage.fillUsername('testuser');
loginPage.fillPassword('Test@1234');
loginPage.clickLogin();
cy.url().should('eq', 'https://example.com/dashboard');
cy.contains('h1', 'Welcome, testuser!').should('be.visible');
});
});The LoginPage class encapsulates all selectors and actions related to the login page. This keeps test code clean and easy to maintain.
The visit() method opens the login page URL. The fillUsername() and fillPassword() methods enter the credentials into the input fields. The clickLogin() method clicks the login button.
In the test file, we create an instance of LoginPage and call these methods in order. After clicking login, we assert that the URL is the dashboard URL and that the welcome heading is visible.
This structure follows the Page Object Model pattern, making tests easier to read and maintain.