How to Implement Automated Tests with Cypress

Posted On: 2 fevereiro 2024 Posted by: Cercal Introduction The importance of testing is fundamental to ensure the quality, reliability, and performance of software. Some of the positive aspects that highlight the relevance of testing in web environments include: Bug detection: Testing allows for the identification of issues in the code, helping to correct them before they reach the production environment, saving time and resources. Ensure compliance with requirements: Testing ensures that the application meets the functional and non-functional requirements defined at the beginning of the development. Improve stability: Regular testing contributes to the software’s stability, reducing the likelihood of failures and unexpected crashes during use. Facilitates maintenance: Automated tests simplify the maintenance process, enabling the quick detection of regressions when new features are added or changes are made. In summary, testing plays a crucial role in the software development life cycle, contributing to the construction of robust, reliable applications capable of meeting user expectations. The Cypress Cypress stands out as a robust and efficient tool for end-to-end test automation, providing a modern and user-friendly approach to ensuring the quality of web applications. Simplicity and clarity: Cypress is known for its simple and clear syntax, making test writing accessible even for those with limited experience in automation. Browser Execution: One of Cypress’ features is the ability to run tests directly in the browser. This provides real-time visibility into the application’s behavior, allowing for quicker and more effective debugging. Real-time Visualization: During test execution, Cypress provides a real-time visualization, allowing developers to observe the tested application step by step. Isolated Environment: Each test in Cypress runs in an isolated environment, ensuring consistency and independence between tests. This contributes to the reliability and reproducibility of test results. Cypress emerges as a comprehensive tool for end-to-end test automation, combining simplicity, speed, and real-time visibility. Its modern approach and distinctive features make it a powerful choice for development teams committed to quality and efficiency in their web applications. Cypress Installation Installing Cypress in a project is relatively simple. Steps to start a project from scratch with Cypress: Start a Node.js project: make sure your Node.js project is up and running. Otherwise, run the following command in the command line to initialize a new Node.js project. npm init -y Install Cypress as a development dependency: Run the following command in the terminal within your project folder to install Cypress as a development dependency: npm i –save-dev cypress Open Cypress for the first time: After the installation is complete, run the following command to open Cypress for the first time. This will create the initial Cypress project structure, including the “cypress” folder and some example files. npx cypress open Configure script in package.json (optional): To simplify the use of Cypress, add scripts to the package.json file. For example: "scripts": { "test": "cypress run", "test:open": "cypress open" } Writing tests with Cypress To start, let’s create a simple HTML form. Create the index.html file in the project’s root folder with the following content: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Example Page</title> </head> <body> <h1>Cypress Test – Example Page</h1> <label for="name">Name:</label> <input type="text" id="name" name="name"> <label for="email">Email:</label> <input type="email" id="email" name="email"> <button id="btn-send">Send</button> <button id="btn-reset">Reset</button> <p id="result"></p> <script> document.getElementById('btn-send').addEventListener('click', function() { var name = document.getElementById('name').value; var email = document.getElementById('email').value; document.getElementById('result').innerHTML = 'Sent: ' + name + ', ' + email; }); document.getElementById('btn-reset').addEventListener('click', function() { document.getElementById('name').value = ''; document.getElementById('email').value = ''; document.getElementById('result').innerHTML = ''; }); </script> </body> </html> Create the file `myfirsttest.cy.js` in `cypress/e2e/1-getting-started/` with the following content: describe("Tests on the Example Page", () => { beforeEach(() => { cy.visit("index.html"); }); it("Should fill in fields and click Send", () => { cy.get("#name").type("John Doe"); cy.get("#email").type("[email protected]"); cy.get("#btn-send").click(); cy.get("#result").should( "have.text", "Sent: John Doe, [email protected]" ); }); it("Should reset fields when clicking Reset", () => { cy.get("#name").type("John Doe"); cy.get("#email").type("[email protected]"); cy.get("#btn-reset").click(); cy.get("#name").should("have.value", ""); cy.get("#email").should("have.value", ""); cy.get("#result").should("not.be.visible"); }); }); Test 1: Should fill in fields and click Send This test checks if the ‘Name’ and ‘Email’ fields can be filled, and if the ‘Send’ button performs the expected action. it('Should fill in fields and click Send', () => { // Fill in the Name and Email fields cy.get('#name').type('John Doe'); cy.get('#email').type('[email protected]'); // Click the Send button cy.get('#btn-send').click(); // Verify if the result is displayed correctly cy.get('#result').should('have.text', 'Sent: John Doe, [email protected]'); }); Test 2: Should reset fields when clicking Reset This test checks if the ‘Name’ and ‘Email’ fields are reset correctly when the ‘Reset’ button is clicked. it("Should reset fields when clicking Reset", () => { // Fill in the Name and Email fields cy.get('#name').type('John Doe'); cy.get('#email').type('[email protected]'); // Click the Reset button cy.get('#btn-reset').click(); // Wait for a short period to ensure the previous action is completed cy.wait(500); // Verify if the fields have been reset cy.get('#name').should('have.value', ''); cy.get('#email').should('have.value', ''); // Verify if the result is no longer visible cy.get('#result').should('not.be.visible'); }); Resultado https://website.mmti.io/wp-content/uploads/2024/01/myfirsttest.cy_.js.mp4 These tests are designed to ensure that user interaction with the fields and buttons on the page works as expected. They also demonstrate Cypress’s ability to handle these interactions effectively. Conclusion Effective implementation and execution of tests are crucial aspects of software development, and Cypress stands out as a powerful tool for end-to-end test automation in web applications. In this tutorial, we explored the installation of Cypress in a project, wrote basic tests, and highlighted some of the key features of the tool. When writing tests with Cypress, we observed the simplicity and clarity of its syntax, making it easy to create and maintain test cases. We explored fundamental commands like cy.get(), cy.click(), and cy.type(), which enable intuitive interactions with page elements. Practical examples of tests covered common scenarios, including navigation, interaction with elements, and result verification. We demonstrated how to create a robust testing environment, from opening a page to checking specific results. Despite the initial challenge of verifying the non-existence of the #result element, we adjusted the approach to handle it, ensuring that the tests are more robust and reliable. In summary, Cypress offers a modern approach to end-to-end test automation, providing simplicity,