How to Write Automated Test Scripts Using Cypress: A Step-by-Step Guide
https://docs.cypress.io/img/guides/overview/v10/real-world-app.png

How to Write Automated Test Scripts Using Cypress: A Step-by-Step Guide

In the landscape of modern web development, automated testing has become a crucial practice for ensuring software quality and accelerating delivery cycles. Among the tools available, Cypress has emerged as a powerful and user-friendly framework for end-to-end testing. Its ease of use, real-time reloading, and robust capabilities make it a popular choice among developers and QA engineers. This article will guide you through the process of writing automated test scripts using Cypress, highlighting key features and best practices.

?

What is Cypress?

Cypress is an open-source testing framework designed for end-to-end testing of web applications. Unlike traditional testing tools, Cypress runs directly in the browser, allowing for real-time testing and debugging. It supports modern JavaScript frameworks like React, Angular, and Vue, and offers a comprehensive set of features for writing reliable and maintainable tests.

?

Setting Up Cypress

Before you start writing test scripts, you need to set up Cypress in your project. Here’s a step-by-step guide:

?

1. Install Node.js:

Make sure Node.js is installed on your system.

You can download it from [nodejs.org](https://nodejs.org/).

?

2. Initialize Your Project:

?? mkdir cypress-tests
  
   cd cypress-tests

   npm init -y        

3. Install Cypress:

?? Add Cypress to your project using npm:

?? npm install cypress --save-dev        

4. Open Cypress:

?? Initialize Cypress and open the Cypress test runner:

?? npx cypress open        

?? This command creates a cypress directory in your project with example tests and configuration files.

?

Writing Your First Cypress Test Script

With Cypress set up, you can now write your first automated test script. Cypress uses Mocha and Chai for writing test cases, which provides a familiar syntax for those experienced with JavaScript testing.

?

1. Create a Test File:

Navigate to the cypress/integration folder and create a new file named example.spec.js.

?

2. Write a Basic Test:

?? Here’s an example of a simple test that verifies the title of a webpage:

?? describe('My First Test', () => {
     
      it('should have the correct title', () => {

       cy.visit('https://example.com');

       cy.title().should('eq', 'Example Domain');

     });

   });        

???Note:

?? - describe and it are Mocha functions used to structure your test cases.

?? - cy.visit navigates to the specified URL.

?? - cy.title retrieves the page title, and should asserts that the title is as expected.

?

Advanced Cypress Features

Cypress offers several advanced features that enhance the testing experience:

?

1. Element Interactions:

?? Interact with elements on the page, such as clicking buttons or typing into fields:

?? it('should login with valid credentials', () => {
   
     cy.visit('https://example.com/login');

     cy.get('input[name="username"]').type('myUsername');

     cy.get('input[name="password"]').type('myPassword');

     cy.get('button[type="submit"]').click();

     cy.url().should('include', '/dashboard');

   });        

2. Assertions and Chaining:

?? Cypress supports chaining multiple commands and assertions:

?? it('should display error message on invalid login', () => {
    
     cy.visit('https://example.com/login');

     cy.get('input[name="username"]').type('invalidUser');

     cy.get('input[name="password"]').type('invalidPass');

     cy.get('button[type="submit"]').click();

     cy.get('.error-message').should('be.visible')

       .and('contain', 'Invalid username or password');

   });        

3. Custom Commands:

?? Create custom commands to reuse code across tests:

?? // cypress/support/commands.js
   
    Cypress.Commands.add('login', (username, password) => {

     cy.visit('https://example.com/login');

     cy.get('input[name="username"]').type(username);

     cy.get('input[name="password"]').type(password);

     cy.get('button[type="submit"]').click();

   });

  

   // Usage in test file

   it('should login with valid credentials', () => {

     cy.login('myUsername', 'myPassword');

     cy.url().should('include', '/dashboard');

   });        

4. Fixtures:

?? Use fixture files to manage test data:

?? // cypress/fixtures/user.json

   {

     "username": "myUsername",

     "password": "myPassword"

   }

    // Test file

     it('should login with valid credentials from fixture', () => {

     cy.fixture('user').then(user => {

      cy.visit('https://example.com/login');
 
      cy.get('input[name="username"]').type(user.username);

       cy.get('input[name="password"]').type(user.password);

       cy.get('button[type="submit"]').click();

       cy.url().should('include', '/dashboard');

       });

   });        

5. Network Stubbing:

?? Mock and control network requests to simulate different server responses:

?? it('should handle API errors gracefully', () => {
    
    cy.intercept('GET', '/api/data', { statusCode: 500, body: { error: 'Server Error' } });

     cy.visit('https://example.com');

     cy.get('.error-message').should('contain', 'Server Error');

   });        

Best Practices

1.?????? Organize Tests:

Structure tests logically using describe and it blocks. Group related tests and use before and after hooks to set up and clean up test environments.

?

1.?????? Use Environment Variables:

Manage environment-specific configurations and secrets using Cypress environment variables.

?

2.?????? Keep Tests Isolated:

Ensure each test is independent and does not rely on the outcome of previous tests.

?

3.?????? Leverage Cypress Dashboard:

Use Cypress Dashboard for test analytics, parallel test execution, and more advanced features. Note that the Dashboard is a paid feature but offers valuable insights and collaboration capabilities.

?

4.?????? Continuous Integration:

?????? ?Integrate Cypress tests into your CI/CD pipeline to automate test execution and feedback.

?

Conclusion

Cypress provides a powerful and user-friendly framework for writing automated test scripts, enabling comprehensive end-to-end testing of web applications. By leveraging its intuitive API, advanced features, and best practices, you can create reliable and maintainable tests that enhance software quality and accelerate development cycles. Whether you’re starting with Cypress or looking to optimize your existing test suite, mastering these techniques will help you leverage Cypress to its fullest potential, ensuring that your applications perform seamlessly across different scenarios and environments.

Christian DeLaphante

C# Test Automation Architect | Mentor

5 个月

Try automating the following scenarios for the following websites: Website - https://magento.softwaretestingboard.com/ Scenarios 1. Place a successful order selecting 3 different items 2. Create an account Website - https://demo.1crmcloud.com Scenarios 1. Create a new contact 2. Generate a report 3. Remove events from activity log Website - https://opensource-demo.orangehrmlive.com Scenarios 1. Add a new employee 2. Update My Info 3. Delete an existing record If you can automate the above websites using those scenarios with Cypress and they are robust and not flaky then we will know whether it's the best tool for test automation or end to end testing. ??

要查看或添加评论,请登录

Tatiana Bernon的更多文章

社区洞察

其他会员也浏览了