Cypress - Basic Commands
Cypress - Essential Commands Overview
Section titled “Cypress - Essential Commands Overview”Cypress offers a rich set of commands to interact with your web application. Here are some of the most commonly used ones:
.and()
Section titled “.and()”Chains an assertion to the previous assertion. It’s an alias of .should() and improves readability when multiple assertions are made on the same subject.
Usage:
// Element should be visible AND enabledcy.get('#submit-button').should('be.visible').and('be.enabled');
// Checkbox with specific value should be checkedcy.get('input[type="checkbox"][value="newsletter"]').should('be.checked');Assigns an alias to a subject (e.g., DOM elements, network requests, fixtures) for later reference within the test. Aliases are accessed using cy.get('@aliasName').
Usage:
// Alias the first list item as 'firstItem'cy.get('ul#my-list > li').first().as('firstItem');// Later in the test...cy.get('@firstItem').should('have.class', 'active');.blur()
Section titled “.blur()”Removes focus from a DOM element that currently has focus.
Usage:
// Type text into an input and then blur itcy.get('#username').type('jane.doe').blur();.check()
Section titled “.check()”Checks radio buttons or checkboxes. Applicable to <input type="radio"> or <input type="checkbox"> elements.
Usage:
// Checks a checkbox with the class 'terms-checkbox'cy.get('.terms-checkbox').check();
// Checks a radio button with a specific valuecy.get('input[type="radio"][value="female"]').check();.children()
Section titled “.children()”Gets the children of a DOM element or a set of DOM elements. Optionally, a selector can be provided to filter the children.
Usage:
// Gets all direct children <li> elements of a <ul>cy.get('ul#main-menu').children('li');.clear()
Section titled “.clear()”Clears the value of an input field or textarea.
Usage:
// Type into an input, then clear itcy.get('#search-box').type('initial text').clear().should('have.value', '');cy.clearCookie()
Section titled “cy.clearCookie()”Clears a specific browser cookie by name.
Usage:
// Clear the 'session_id' cookiecy.clearCookie('session_id');cy.clearCookies()
Section titled “cy.clearCookies()”Clears all browser cookies for the current domain and subdomain.
Usage:
// Clear all cookies before a testcy.clearCookies();cy.clearLocalStorage()
Section titled “cy.clearLocalStorage()”Clears all localStorage data for the current origin. Can also clear specific keys if a key name is provided.
Usage:
// Clear all local storage datacy.clearLocalStorage();
// Clear a specific item from local storagecy.clearLocalStorage('userPreferences');.click()
Section titled “.click()”Clicks a DOM element. Cypress ensures the element is actionable before clicking.
Usage:
// Click on a button with id 'login-btn'cy.get('#login-btn').click();cy.contains()
Section titled “cy.contains()”Gets the DOM element containing the specified text. If a selector is provided first, it searches within those elements.
Usage:
// Get an element containing the text 'Welcome'cy.contains('Welcome');
// Get a button within a form that contains the text 'Submit'cy.get('form#user-form').contains('button', 'Submit');.dblclick()
Section titled “.dblclick()”Double-clicks a DOM element.
Usage:
// Double-click an element with id 'edit-icon'cy.get('#edit-icon').dblclick();.debug()
Section titled “.debug()”Pauses the test and opens browser developer tools, logging the current subject. Useful for debugging.
Usage:
// Pause and debug after getting the elementcy.get('#user-profile').debug();cy.document()
Section titled “cy.document()”Gets the window.document object of the currently active page.
Usage:
cy.document().should('have.property', 'charset').and('eq', 'UTF-8');.each()
Section titled “.each()”Iterates over an array-like subject (e.g., a collection of DOM elements).
Usage:
// Iterate through each list item and check its textcy.get('ul#todo-list > li').each(($li, index, $list) => { cy.log(`Item ${index}: ${$li.text()}`);});.end()
Section titled “.end()”Ends the current chain of commands. This is rarely needed, as Cypress commands typically flow naturally. It can be used to revert to a previous subject if you’ve temporarily changed it (e.g., within a .within() block, though .within() handles this automatically).
Usage:
// Example: (though often not necessary)cy.get('form').within(() => { cy.get('input[name="username"]').type('test');}).end() // Subject is back to 'form'.should('have.class', 'submitted');Gets the DOM element at a specific index within a collection of elements.
Usage:
// Get the third <td> element in a table rowcy.get('table#data-table tr:first-child td').eq(2).should('contain', 'Status');cy.exec()
Section titled “cy.exec()”Runs a system command from the project’s root. Useful for tasks like seeding a database or running scripts.
Usage:
// Example: Run a script to reset database statecy.exec('npm run db:reset');.find()
Section titled “.find()”Gets descendant DOM elements of the current subject, filtered by a selector.
Usage:
// Find all <td> elements within a specific table rowcy.get('tr#user-row-123').find('td');.first()
Section titled “.first()”Gets the first DOM element within a collection of elements.
Usage:
// Get the first <td> in each table rowcy.get('table#data-table tr td').first();cy.get()
Section titled “cy.get()”Gets one or more DOM elements by selector or alias. This is one of the most fundamental commands.
Usage:
// Get an element by IDcy.get('#main-content');// Get all elements with class 'item'cy.get('.item');// Get an aliased elementcy.get('@myAlias');cy.getCookie()
Section titled “cy.getCookie()”Gets a specific browser cookie by its name.
Usage:
cy.getCookie('user_session').should('have.property', 'value', 'abcdef12345');cy.getCookies()
Section titled “cy.getCookies()”Gets all browser cookies.
Usage:
cy.getCookies().should('not.be.empty');cy.go()
Section titled “cy.go()”Navigates backward or forward in the browser’s history.
Usage:
// Navigate backcy.go('back');// Navigate forwardcy.go('forward');// Navigate back by 2 pagescy.go(-2);cy.visit()
Section titled “cy.visit()”Visits a remote URL or a local HTML file.
Usage:
cy.visit('https://www.example.com');cy.visit('/about-us'); // Relative to baseUrl in cypress.config.jscy.visit('app/index.html'); // Local file.next()
Section titled “.next()”Gets the immediately following sibling DOM element of the current subject.
Usage:
// Get the next list item siblingcy.get('li.active-item').next().should('have.class', 'next-item');.parent()
Section titled “.parent()”Gets the parent DOM element of the current subject.
Usage:
// Get the parent <div> of an element with class 'child-element'cy.get('.child-element').parent('div.parent-container');.should()
Section titled “.should()”Creates an assertion. Cypress retries the assertion until it passes or times out.
Usage:
// Assert that an element is visiblecy.get('#error-message').should('be.visible');// Assert that an input has a specific valuecy.get('#name-input').should('have.value', 'John Doe');cy.wait()
Section titled “cy.wait()”Pauses the test for a specified duration in milliseconds or waits for an aliased resource (like a network request) to resolve. Using cy.wait(milliseconds) for arbitrary pauses is generally discouraged; prefer using assertions that retry or waiting for aliased routes.
Usage:
// Wait for 1 second (use sparingly)cy.wait(1000);
// Wait for an aliased network requestcy.intercept('GET', '/api/users').as('getUsers');cy.visit('/users');cy.wait('@getUsers').its('response.statusCode').should('eq', 200);cy.title()
Section titled “cy.title()”Gets the document.title of the currently active page.
Usage:
cy.title().should('eq', 'My Application - Dashboard');cy.viewport()
Section titled “cy.viewport()”Controls the screen size and orientation for your tests. Can accept width/height numerical values or preset names (e.g., ‘iphone-6’).
Usage:
// Set viewport to 1280px width and 720px heightcy.viewport(1280, 720);
// Use a preset viewport sizecy.viewport('macbook-15');cy.log()
Section titled “cy.log()”Prints a message to the Cypress Command Log. Useful for debugging or providing context during test execution.
Usage:
cy.log('Starting login sequence...');cy.get('#username').type('user');cy.log('Username entered.');cy.reload()
Section titled “cy.reload()”Reloads the current page, similar to the browser’s refresh button.
Usage:
cy.reload();// Reload without using cachecy.reload(true);