Basic Commands in Cypress
Last Updated :
13 May, 2024
Cypress being a modern, full-stack test runner, developers are able to create maintainable web application unit tests which turn out to be reliable and supportable. It gives a palette of commands for interacting with web elements that allows for various actions to happen, and it is a very useful tool for these automations.
In this piece of writing, we will discuss how one can write basic Cypress commands, their respective syntaxes, and the ways they can be used.
What is Cypress Commands?
Cypress directives are used to create the scenarios of your test scripts. They allow to work with the web elements in your tests, do what is necessary, validate the expected results, and run the tests sequentially. The cypress commander library has a robust command set, each designed for different situations or scenarios. This command could be chained amongst other commands, which can create elaborate scenario for testing.
Cypress Commands
1. cy.visit()
The cy.visit() command is used to navigate to a specific URL in the browser. It's typically the first command you'll use in your test suite to load the web application you want to test.
cy.visit('https://example.com')
In this example, Cypress will navigate to https://example.com.
2. cy.get()
The cy.get() command is used to retrieve one or more elements from the DOM (Document Object Model) based on a selector. It's a fundamental command that you'll use extensively in your tests to interact with various elements on the page.
cy.get('input[type="email"]')
In this example, Cypress will get the input element with the attribute type="email".
3. cy.contains()
The cy.contains() command is used to retrieve one or more elements from the DOM that contain the specified text content.
cy.contains('Submit')
In this example, Cypress will get an element that contains the text "Submit".
4. cy.click()
The cy.click() command is used to simulate a click event on an element.
y.get('button').click()
In this example, Cypress will click on the button element.
5. cy.type()
The cy.type() command is used to type text into an input field or text area.
cy.get('input[name="username"]').type('johndoe')
In this example, Cypress will type "johndoe" into the input field with the attribute name="username".
6. cy.clear()
The cy.clear() command is used to clear the value of an input field or text area.
cy.get('textarea').clear()
In this example, Cypress will clear the value of the textarea element.
7. cy.url()
The cy.url() command is used to get or assert the current URL of the page.
cy.url().should('include', '/dashboard')
In this example, Cypress will assert that the current URL includes "/dashboard".
8. cy.title()
The cy.title() command is used to get or assert the current title of the page.
cy.title().should('eq', 'My Website')
In this example, Cypress will assert that the current page title is equal to "My Website".
9. cy.reload()
The cy.reload() command is used to reload the current page in the browser.
cy.reload()
In this example, Cypress will reload the current page.
10. cy.wait()
The cy.wait() command is used to wait for a specified amount of time or until a condition is met.
cy.wait(5000) // Wait for 5 secondscy.get('#loading').should('not.exist').then(() => { // Code to execute after the loading element is no longer present})
In the first example, Cypress will wait for 5 seconds before proceeding to the next command. In the second example, Cypress will wait until the element with the ID "loading" no longer exists on the page before executing the code in the then callback.
11. cy.should()
The cy.should() command is used to make an assertion about the current subject (e.g., an element, response, or value).
cy.get('span').should('have.text', 'Hello, World!')
In this example, Cypress will assert that the span element has the text "Hello, World!".
12. cy.intercept()
The cy.intercept() command is used to intercept a network request and provide a mock response.
cy.intercept('GET', '/api/users', { fixture: 'users.json' })
In this example, Cypress will intercept a GET request to /api/users and return the data from the users.json fixture file.
13. cy.request()
The cy.request() command is used to send a network request without loading the page.
cy.request('POST', '/api/login', { username: 'johndoe', password: 'mypassword' })
In this example, Cypress will send a POST request to /api/login with the specified request body.
14. cy.route()
The cy.route() command is used to create a route for network requests that can be waited on or stubbed.
cy.route('POST', '/api/users').as('createUser')
In this example, Cypress will create a route for POST requests to /api/users and alias it as "createUser".
15. cy.fixture()
The cy.fixture() command is used to load data from a fixture file.
cy.fixture('users.json').then((users) => { // Code to execute with the users data})
In this example, Cypress will load the data from the users.json fixture file and pass it to the callback function.
16. cy.readFile()
The cy.readFile() command is used to read the contents of a file and pass it to the callback function.
cy.readFile('cypress/fixtures/example.json').then((json) => { // Code to execute with the JSON data})
In this example, Cypress will read the contents of the example.json file and pass the JSON data to the callback function.
17. cy.writeFile()
The cy.writeFile() command is used to write data to a file.
cy.writeFile('cypress/fixtures/output.txt', 'Hello, World!')
In this example, Cypress will write the string "Hello, World!" to the output.txt file in the fixtures directory.
The cy.scrollTo() command is used to scroll the browser window or an element to the specified position.
cy.get('#footer').scrollTo('bottom')
In this example, Cypress will scroll to the bottom of the element with the ID "footer".
19. cy.hover()
The cy.hover() command is used to trigger a hover event on the specified element.
cy.get('.dropdown-menu').trigger('mouseover')
In this example, Cypress will trigger a mouseover event on the element with the class "dropdown-menu".
Conclusion
Cypress delivers with an assortment of commands so developers can write dependable and resilient tests for web applications. The introductory article commands, such as cy. , are covered in this post that will also take you through the subsequent ones, like create or destroy objects, get or set variables, etc. , they serve as proper bricks to construct strong test cases. The tasks are taken care of by the commands when they are combined and they allow you to embrace web elements and to also make expected behaviors of your application assertions.
Similar Reads
Automation Testing - Software Testing
Automated Testing means using special software for tasks that people usually do when checking and testing a software product. Nowadays, many software projects use automation testing from start to end, especially in agile and DevOps methods. This means the engineering team runs tests automatically wi
15+ min read
Automation Testing Roadmap: A Complete Guide to Automation Testing [2025]
Test automation has become a vital aspect of the Software Development Life Cycle (SDLC), aimed at reducing the need for manual effort in routine and repetitive tasks. Although manual testing is crucial for ensuring the quality of a software product, test automation plays a significant role as well.
9 min read
How to Start Automation Testing from Scratch?
Automation Testing is the practice of using automated tools and scripts to execute tests on software applications, reducing manual effort and increasing efficiency. Starting automation testing from scratch involves several key steps, including selecting the right automation tool, identifying test ca
8 min read
Benefits of Automation Testing
In today's fast-paced software development landscape, integrating automation into development and testing processes is crucial for staying competitive. Automation testing offers numerous benefits, including cost savings, faster feedback loops, better resource allocation, higher accuracy, increased t
4 min read
Stages of Automation Testing Life Cycle
In this article, we will explore the phases and methodologies involved in automation testing and the phases of the automation testing lifecycle. We'll cover everything from scoping your test automation to creating a solid test plan and strategy. You'll also learn about setting up the perfect test en
12 min read
Top Automation Testing Books For 2024
In this article, we can explore the top 10 books for automation testing, providing a top-level view of each book's content material and why it's worth considering for everybody interested in this sector. Table of Content Top 10 Books for Automation Testing BooksConclusionFAQs on Top Automation Test
12 min read
Top Test Automation mistakes and Tips for QA teams to avoid them
In the dynamic landscape of software testing, avoiding common test automation pitfalls is crucial for QA teams aiming for efficient and successful testing processes. This article delves into prevalent errors in test automation and provides valuable insights on how QA teams can steer clear of these m
7 min read
Essential Skills for a Successful Automation Tester
In the domain of software testing, automation plays a crucial role in ensuring efficiency, accuracy, and speed. However, to be a successful automation tester, one must possess a specific set of skills beyond just technical proficiency. This article explores the essential skills required for automati
6 min read
Steps to Select the Right Test Automation tools
Selecting the right test automation tools is critical for ensuring efficient and effective testing processes in software development projects. In this article, we will discuss the key steps involved in choosing the most suitable automation tools for your project needs. From understanding project req
5 min read
Best Test Automation Practices in 2024
Test Automation continues to evolve with new technologies and methodologies emerging each year. In 2024, staying updated with the latest best practices is crucial for efficient and effective testing processes. From robust test design to continuous integration and deployment, this article explores th
7 min read