How to Write Your First Cypress Test [With Examples]

Kailash Pathak

Posted On: March 14, 2024

view count52134 Views

Read time21 Min Read

Choosing an ideal testing framework, especially with a different technology stack, can be challenging for new users, particularly those switching from other testing tools to Cypress. This shift might involve adapting to unfamiliar technological stacks. However, Cypress addresses this challenge by providing an in-built tool called ‘Cypress Studio’.

There are two ways to write your first Cypress test:

  1. Using ‘Cypress Studio’
  2. Writing your script

In this blog, we will discuss how a new user can start his journey in Cypress and efficiently write the first Cypress test. You will also see the implementation of Cypress tests on local machines and cloud grids.

What is Cypress Studio?

Cypress Studio provides a user-friendly interface for test case creation. It is a record and playback tool that captures user interactions with the application being tested. Using Cypress Studio, you can record user interactions in JavaScript. Whatever the step you follow in UI, Cypress Studio automatically records the steps in the backend in the test file

Here are some benefits of using Cypress Studio:

  • Record and Playback
  • The interface supports a record-and-playback mechanism, allowing users to record their interactions with the application. This feature is particularly useful for users who may not have extensive programming knowledge, enabling them to create test scripts without manually writing code.

  • Codeless Test Automation
  • One of the primary advantages of Cypress Studio is its codeless approach. Users can create and edit test scripts without writing code, making it accessible to individuals with limited programming knowledge. This lowers the entry barrier for manual testers and non-developers to participate in test automation.

  • Reduce Learning Curve
  • The simplicity and clarity of Cypress Studio’s interface reduce the learning curve for users new to automated testing. This enables teams to onboard new members quickly and encourages broader team participation in the testing process.

  • Fast Script Creation
  • Cypress Studio records all the steps of UI interaction so if someone wants to create the script fast he/she can record the script and can re-use the record script for further development.

  • Debugging the script
  • Debugging in Cypress Studio involves examining and modifying the recorded script to ensure it accurately reflects the intended test scenario. Users can edit and debug the recorded script. This flexibility allows users to tweak tests as needed, which strikes a balance between codeless development and human scripting.

In the next section, you will see how we can set up Cypress Studio.

Setting up Cypress Studio

Before setting up Cypress Studio, you need to install Cypress. You can install Cypress using the following commands:

npm install cypress --save-dev

or

yarn add cypress --dev

In the screenshot below, you can see that the latest version of Cypress has been installed. However, when writing this blog on your first Cypress test, Cypress’s latest version was 13.6.2.

Cypress

The next step is to enable Cypress Studio. To enable this feature, we must set experimentalStudio:true in the configuration file.

configuration

We have updated the cypress.config.js (configuration file)to enable the Cypress Studio feature. Now, the next step is to record the script.

Ways of Recording the Script

We can record the script using Cypress Studio. Below are two options to record the script:

  • Create a test with Cypress Studio
  • Add New Test

Using the ‘Create test with Cypress Studio’ Option

You should have some existing test cases before recording using the option ‘Create test with Cypress Studio’ in Cypress Runner.

Let’s run the following command to open Cypress Runner.

yarn cypress open

After opening the Cypress Runner, run an existing test case. As we run the command, it will open Cypress Runner with the option ‘Create test with Cypress Studio.

link

Clicking on the ‘Create test with Cypress Studio’ link in the Cypress Test Runner initiates Cypress Studio and prompts you to provide the URL of the application you want to test.

provide

Let’s record the test scenario below.

  1. Open the site https://ecommerce-playground.lambdatest.io/.
  2. Click on My Account.
  3. Enter User Name.
  4. Enter Password.
  5. After logging in, log out of the application.

Once we record the above scenario, we will be asked to save the recorded commands.

providing

Let’s save the command that is recorded by providing the recorded script’s name.

automatically

Once we save the recorded script, it is automatically saved under the path ‘e2e/LTCypressStudio’. This path indicates the location within your Cypress project where the test script file is stored.

Below is the recorded script where you can see the generated code. Once the recording is done, it will end with line /*==== End Cypress Studio ==== */

We have seen above one option to record the script by clicking on the link ‘Create test with Cypress Studio’ from Cypress Runner.

Let’s see the second option, i.e., ‘Add New Test’ to record the script.

Adding New Test

This option is used when you want to create a completely new Cypress test. It lets you define and execute specific test scenarios in a new file.

us to ente

As we click on ‘Add New Test,’ it will ask us to enter the URL. Let’s record the scenario below.

  1. Open the site https://www.lambdatest.com/selenium-playground/auto-healing.
  2. Enter User Name.
  3. Enter Password.
  4. Click on the Submit button.

Commands

After recording, click Save Commands. Let’s give the name ‘LambdaTestAddNewTest.’

Studio

Once we save the script by giving some name, the test case executes and passes successfully. Below is the recorded script by Cypress Studio.

Modifying the Existing Script

Using Cypress Studio, we can add new scripts and update the existing script with more commands.

Add Commands to Test

This option is useful when adding Cypress commands to an existing test. It allows you to extend the functionality of an already defined test or modify its behavior by incorporating additional Cypress commands.

scripts

Let’s update one of the previously recorded scripts where we are login into https://ecommerce-playground.lambdatest.io/

Cover the below scenario to update the existing script using Cypress Studio.

  1. After logging in, search for the text ‘HP.’
  2. Click on the first item in the search results.
  3. Click on Add to Cart.
  4. Click on View Cart.

Click on ‘Add Commands to Test’ from Cypress Runner.

Add Commands to Test

As part of Cypress Studio, when we click ‘Add Commands to Test,’ the complete test case is rerun. In our case, the user is logged in to the site. After that, we can search for the product ‘HP,’ add it to the cart, and redirect to the View Cart page.

The Cypress command log shows that each updated step is recorded with the ‘Save Commands’ button. Once you click the ‘Save Commands’ button, the script is updated with more steps.

scenario

The screenshot below shows that once the scenario is completed, the script will be updated with some more steps. You can see some more steps are added, so you can update the existing script using Cypress Studio. Below is the script that is recorded.

swiftly

Cypress Studio is beneficial for those seeking to swiftly generate test scripts without needing to code, making it especially advantageous for novices getting started with Cypress.

Despite being a handy tool for rapidly creating code-free test scripts, Cypress Studio encounters difficulties when handling intricate test scenarios or scenarios incorporating dynamic data.

So far, we have seen how you can record scripts using the built-in tool Cypress Studio. In the next section, you will see how we can create a Cypress test case by writing our script.

Writing First Cypress Test Script

Writing Cypress scripts manually refers to crafting test code directly using JavaScript or TypeScript rather than relying on visual recording tools like Cypress Studio. Cypress uses Mocha as its default automation testing framework.

When you install Cypress, it automatically includes Mocha, and you don’t need to install Mocha separately to use it with Cypress. Integrating Mocha with Cypress provides a structured and organized way to write end-to-end tests. Cypress leverages Mocha’s syntax, which includes describe and it blocks for test organization, as well as hooks for setup and teardown, to create a clear and readable testing structure.

Before writing the script, we need to set up Cypress. Below are some of the steps that we have to follow.

Step 1: Install Cypress

To write the script on your own, let’s set up Cypress using the following commands:

npm install cypress —-save-dev

or

yarn add cypress —-dev

The screenshot below shows that Cypress’s latest version was 13.6.2 when this blog on writing your first Cypress test was written.

below

After installation, the folder structure looks like the one below, with different folders given in brief detail below.

purpose

The table below summarizes the purpose of each directory and file within the Cypress project.

Directory/File Description
cypress/ Directory for containing all Cypress-related files.
fixtures/ Directory for storing static data (e.g., JSON files) used as test fixtures.
e2e/ Directory where test files are stored: Cypress looks for test files in this directory by default.
support/ Directory containing the commands.js file. It is used to extend Cypress commands and customize its behavior.
Cypress.config.js File where various options and Cypress behavior can be set.
package.json File holding metadata about the project and its dependencies.

Step 2: Create a Test File

Create a new test file under cypress/e2e/ to run the e2e test case. Let’s give a name to the file, e.g., lambdatest_test_spec.cy.js

initial

Step 3: Write Your Test

As we mentioned above, Cypress supports the Mocha framework. Therefore, we must grasp key concepts before proceeding to our initial script.

describe() Block

Mocha uses the describe and it blocks to structure test suites and individual test cases.describe() is used to group tests.

cases

it() Block

it() is used to define individual test cases.

teardown

Hooks

Mocha supports hooks such as before(), beforeEach(), after(), and afterEach(). Cypress utilizes these hooks for setup and teardown tasks, like preparing the test environment and cleaning up before running tests.

libraries

Assertions

Mocha itself doesn’t include built-in assertion libraries. Cypress, however, provides its assertion library and extends Mocha with Chai assertions. Cypress uses Chai assertions to assert conditions in your tests.

Some of the Examples are .should(‘have.text’, ‘Expected Text’),.should(‘not.equal’, ‘Expected Text’),.should(‘exist’),.should(‘not.be.disabled’), .should(‘have.class’, ‘active’), etc.

Examples

Excluding the Tests

You can use the .skip() method to exclude a specific Cypress test. This method can be applied to a Cypress test or a description block.

Mocha itself doesn't include built-in assertion libraries

Excluding the Tests

You can use the .skip() method to exclude a specific Cypress test. This method can be applied to a Cypress test or a description block.

You can use the .skip() method

The describe.skip() function in Cypress is used to skip the entire test suite within the describe block. Here’s an example:

 describe.skip() function in Cypress is used to skip

Including the Tests

You can use the .only() method to run only specific tests or test suites during the test execution. When you use .only on a Cypress test or a suite, only that test or suite will be executed, and all other tests without .only will be skipped.

.only() method to run only specific tests

So far, we have discussed some concepts required of a user writing his script for the first time. Let’s now put that knowledge into practice by crafting a simple Cypress Script.

Let’s write the script for the below scenario.

  1. Open the URL https://ecommerce-playground.lambdatest.io/index.php?route=account/login.
  2. Enter Email.
  3. Enter Password.
  4. Click on the Login button.
  5. Search product ‘VAIO.’
  6. Click the first product from the search result.
  7. Verify that the searched product name should contain the text ‘Sony VAIO.’

Open lambdatest_test_spec.cy.js and write a simple Cypress test to visit a website, log in, and search for the product.

Code Walkthrough

Let’s do a code walkthrough to understand the script in detail.

describe Block

describe(“LambdaTest Login”, () => { … }): This block represents a test suite named ‘Lambdatest Login’ that contains multiple Cypress test cases related to the LambdaTest login functionality.

test suite named ‘Lambdatest Login’

Open the URL

Visit the specified URL, which is the login page of the LambdaTest application.

login page of the LambdaTest application

Login into the application

Enter the Email and Password input fields, enter the respective values, and click the Login button.

Enter the Email and Password input fields

In the script, we used different locator strategies to interact with elements on the web page. Locators identify and target HTML elements, allowing Cypress to perform actions like typing text, clicking buttons, etc.

Here is the detail of each locator used here:

[id=”input-email”]: Targets the input element with the ID attribute set to “input-email.”

input element with the ID attribute

[id=”input-password”]: This function targets the input element with the ID attribute set to “input-password.”

 input element with the ID attribute set to input-password.

[type=”submit”]: This function targets the Submit button(s). The .eq(0) selects the first matching button.

Submit button(s). The .eq(0) selects the first matching button.

Search the Product

You can search the data by entering a value in the input field, ‘VAIO,’ and clicking the Search button.

entering a value in the input field, ‘VAIO,’

[name=”search”]: This function targets the input element with the name attribute set to “search.”

name attribute set to search.

[type=”submit”]: This function targets the Submit button(s). The .eq(0) selects the first matching button.

function targets the Submit button(s)

Verify Product after search

Verifies that the search results page contains the text “Sony VAIO.”

page contains the text Sony VAIO

Step 4: Execute the Test Case

There are different ways of executing the Cypress test cases.

  • Headed mode: where we can see all executing steps in the browser window.
  • Headless mode: where we execute tests without loading a complete web browser.

Running Test in Headed Mode

To execute the Cypress test case in the headed mode locally, we must run the following command:

yarn cypress open

or

npx cypress open

As we run the command, it will open the below screen.

As we run the command, it will open the below screen

There are two options: E2E testing and Component Testing.

E2E Testing: E2E testing allows users to simulate user interactions, navigate through the application, and validate the application’s behavior as a whole.

Component Testing: Component testing focuses on testing individual application components in isolation. Component testing aims to verify that each application part behaves as expected independently of the other components.

Select E2E Testing from the above screenshot, then select the desired browser for testing. Finally, launch the Cypress Runner to initiate the testing environment.

 select the desired browser for testing

Click on ‘lambdatest_test_spec.cy.js’ to start executing the tests, and finally, you will see all test steps passed.

Click on ‘lambdatest_test_spec.cy.js’

Running Test in Headless Mode

By default, Cypress runs in ‘headless mode,’ where the browser runs in the background without opening a visible browser window.

The command to run the Cypress test case in headless mode is:

yarn cypress run

or

npx cypress run

The screenshot below shows that all test cases are executed successfully in a headless browser.

all test cases are executed successfully

There are some other commands that you can use to execute the test cases.

Run a full test present in the e2e folder in the Headless mode:

Use the command:

npx cypress run

or

yarn cypress run

Run a particular test case on the default browser in the Headless browser:

The default browser is Electron when you run test cases in headless mode. Use the following command to execute a particular test case on the default browser:

npx cypress run --spec "cypress/e2e/lambdatest/lambdatest_test_spec.cy.js"

t browser is Electron when you run test cases in headless mode

Execute test case on a particular browser in the Headless mode:

Use the following command to execute a specific test case on a particular browser. In this case, we are running on the Chrome browser in headless mode.

npx cypress run --browser chrome --spec "cypress/e2e/lambdatest/lambdatest_test_spec.cy.js"

execute a specific test case on a particular browser

So far, we have explored creating a test script using Cypress Studio and saw how to write the script manually. We have also reviewed different approaches for running these test cases in a local environment. Now, let’s see how we can execute the test cases in the cloud.

Running Cypress test cases in the cloud has various benefits. Cloud-based testing platforms provide scalability, allowing you to scale your testing infrastructure based on the project’s needs. They also enable parallel testing, allowing you to run multiple tests concurrently.

There are various cloud-based platforms in the market. LambdaTest emerges as a standout choice. LambdaTest is an AI-powered test orchestration and execution platform that lets you perform manual and automation testing at scale with over 3000+ browsers and OS combinations to help you automate Cypress test cases on the cloud. It also offers access to real devices and browsers, providing a more accurate simulation of how end-users will experience your web application.

How to Automate Your First Cypress Test on Cloud?

Running Cypress test cases on the cloud is crucial for comprehensive and accurate testing of modern web applications. As cloud testing environments like LambdaTest gain prominence, it becomes imperative to validate that the infrastructure supports the intricacies of testing. This ensures that Cypress test cases can be tested in cloud-based environments, guaranteeing the application’s reliability and functionality in real-world scenarios.

You can accelerate Cypress testing and reduce test execution time by multiple folds by running parallel tests on LambdaTest across multiple browsers and OS configurations.

Subscribe to the LambdaTest YouTube Channel for the latest updates on tutorials around Selenium testing, Cypress e2e testing, and more.

As we execute the test cases on the LambdaTest platform, we must configure our tests for the LambdaTest Cypress cloud grid.

Prerequisite:

The Username and Access key can be obtained from the LambdaTest Dashboard.

Configuring Cypress Test on LambdaTest

Step 1: Install the CLI

The command-line interface of LambdaTest enables us to execute your Cypress tests on LambdaTest. Use the Cypress CLI command via npm, as shown below.

npm install -g lambdatest-cypress-cli

Step 2: Generate lambdatest-config.json

Under the root folder, configure the browsers you want to run the tests. Use the init command to generate a sample lambdatest-config.json file or create one from scratch. Use the below command.

lambdatest-cypress init

In the generated lambdatest-config.json file, pass the information below. Fill in the required values in the lambdatest_auth, browsers, and run_settings sections to run your tests.

In the file below, we pass three browsers (Chrome, Firefox, and Electron) and run the test case in two browsers simultaneously.

Github

Run the below command to execute the test case on the LambdaTest.

lambdatest-cypress run --sync=true

As we run the above command, test execution starts, and test cases are run in parallel on the LambdaTest platform.

Test Case Execution

As we execute the test cases in the screenshot below, both test cases start executing in browsers (Chrome, Firefox) parallelly, and we can see the detailed report in the LambdaTest dashboard.

LambdaTest Web Automation Dashboard offers users a convenient and intuitive interface to oversee test results, review test outcomes, and utilize various platform features. It enables live interactive testing, offering users a real-time view of the website or web application they are testing on a specific browser and operating system.

The screenshot below shows the test case starting to execute in browsers (Chrome, Firefox, and Electron).

test case starting to execute in browsers

The screenshot below shows that test cases are passed in the browser (Chrome, Firefox, and Electron).

Here is the console log of executed test cases in the Chrome browser. You can see that three of the test cases have passed on the LambdaTest Grid.

 console log of executed test cases

Here is the console log of executed test cases in the Firefox browser. You can see that three test cases have passed on the LambdaTest Grid.

 executed test cases in the Firefox browser.

Here is the console log of executed test cases in the Electron browser. You can see that three of the test cases have passed on the LambdaTest Grid.

 log of executed test cases in the Electron browser.

If you’re a developer or tester looking to elevate your skills with Cypress, consider diving into the Cypress 101 certification to stay ahead of the game.

Conclusion

You have taken a comprehensive journey into Cypress test automation, breaking down the process step by step with live examples. You have also seen how to write the test case using the Cypress built-in tool ‘Cypress Studio’ and the manual script-writing process. Furthermore, you’ve explored the steps a new user can take to commence their Cypress experience and outlined effective strategies for starting to write scripts. Also, different ways of recording the script and how to update the existing script.

Furthermore, we’ve discussed the integration of LambdaTest, an AI-powered test orchestration and execution platform, and how it enhances the capabilities of Cypress automation. By seamlessly running our Cypress tests across different browser versions and platforms, you can ensure our applications’ compatibility and reliability in diverse environments. This integration empowers you to deliver high-quality web experiences to users across the digital landscape.

Frequently Asked Questions (FAQs)

What is Cypress testing for?

Cypress testing is primarily used to automate the testing of web applications. It allows developers and QA engineers to write, run, and debug tests directly within the browser. Cypress provides a comprehensive testing framework that facilitates end-to-end testing, integration testing, and unit testing of web applications. It enables testers to simulate user interactions, such as clicking buttons, filling out forms, navigating through the application, and then asserting expected behaviors and outcomes. Overall, Cypress testing helps ensure web application functionality, performance, and reliability across various browsers and environments.

What are Cypress function tests?

Cypress function tests, also known as functional tests, are automated tests used to verify the functionality of web applications. In Cypress, function tests involve writing test scripts to simulate user interactions with the application’s features and functionalities. These tests validate whether the application behaves correctly according to its specifications and requirements.

Author Profile Author Profile Author Profile

Author’s Profile

Kailash Pathak

Currently working as Sr. Quality Lead Manager in a US-based MNC company. Where I am responsible for setting up the overall QA Automation strategy and ensuring that we deliver a high-quality product to our end users. Apart from my role, I have involved myself in educating the community about Software Testing and Test Automation. I am a Blogger and YOUTUBER. I have written a couple of blogs which can find out on my site https://qaautomationlabs.com/

Blogs: 9



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free