Cypress Examples
Static site with Cypress examples tested right from the Markdown sources
Commands
Commands drive your tests in the browser like a real user would. They let you perform actions like typing, clicking, xhr requests, and can also assert things like "my button should be disabled".
Querying
Traversal
- children
- closest
- eq
- filter
- find
- first
- last
- next
- nextAll
- nextUntil
- not
- parent
- parents
- parentsUntil
- prev
- prevAll
- prevUntil
- siblings
- Actions
Viewport
Location
Window
Assertions
- Implicit Assertions
- Explicit Assertions
- Should with callback function
- Multiple assertions
- Comparing arrays
- Custom assertions
Navigation
Aliasing
Waiting
Misc
Connectors
Network Requests
Local Storage
Files
Cookies
Spies, Stubs & Clocks
Utilities
Utilities give you access to methods from other commonly used libraries.
Cypress API
The Cypress API enables you to configure the behavior of how Cypress works internally. You can do things like access Environment Variables, change configuration, create custom commands, and more.
Recipes
Miscellaneous recipes
- Confirm the text changes after the click
- Confirm the counter is incremented after the click
- Checking the length of the list after adding or deleting an item
- CSS class name examples
- Iterate over elements using
.each
command - Non-breaking space
- Set nested property inside the environment object when using Cypress.env
- Find elements by exact class or text
- Get the inner text of a list of elements
- Retry-ability examples
- Get multiple fields at once
- Find an object in the array
- Wait for data to be set
- Return value from .within() command
- Confirm an attribute of an element
- Number of rows matches a number in an element
- Find elements with subelements
- Confirm the sorted lists
- static list
- a table is sorted by column
- Confirm the sorted attributes
- Overlapping elements on the page
- Search part of the list
- Add a custom data-... attribute assertion
- Pseudo CSS selectors like
:link
,:empty
,::before
- Create long text using
Cypress._.repeat
function - Detect duplicate values by text or by attribute
- Save multiple elements under aliases
- Type characters one by one into separate input elements
- Sibling elements using
.next
and CSS selector+
- Collect headings from the page and save as a JSON file
- Querying SVG example
- SVG Loader goes away example
- Confirm the input element trims spaces
- Completely replace
cy.then
command withcy.later
command - Get the HTML comment DOM node
- Get the data from
<script type='text/plain'>info</script>
DOM elements - Check if an image loads
- See the full assertion message without truncated text
- Use the match assertion correctly
- Find elements with the given computed style
- Check the results of multiplication shown on the page
- Parse numbers in the text
- Parse account number with retries
- Get the value of an input element
- Combine two jQuery objects into one in the recipe combine lists
- Confirm the phone number after replacing all
-
characters - Check if a list contains the given text
- Hide the entered text and intercept the form submission
- Get input elements with the given value
- Check number format
- Be careful with instanceof checks
- Empty child elements before comparing the text
- Empty and non-empty elements using
:empty
and:not(:empty)
selectors - Get the own text of an element
- Verify the shown price is within certain dollar range
- Click each item
- Find duplicates
- HTML Dialog element examples
- Compare two numbers on the page
- Compare attribute values
- Change textContent
- Check element style
- Keep it simple
- Find and Click The Accordion With A Button
- Check meta tags and page title
- Confirm the text from the first element is present in the second element
- Confirm the input element clears non-number input within a certain time limit
- Get the last item of an array
- Cannot insert new Cypress commands out-of-band
- Test the prefers-color-scheme CSS
- Listen to Cypress events
- Grab the second matching element by text
- Check the messages the application logs to the
console
object and fail if there is an error message - Confirm the two elements have equal attribute value
- Pick even, odd, or custom index elements using jQuery pseudo-classes like
:even
,:odd
,eq()
,gt()
, andlt()
- Input value matching a regular expression
- Select by attribute examples
- Confirm the input element has a value
- Array includes another array
- Get the element's text without text from a child element
- Get Elements By Attribute That Starts With String X
- How to escape a selector
- A few examples of CSS and jQuery selectors
- Checking if an element has either of the two attributes or certain values of the attribute
- Remove elements using jQuery method
.remove
- Find the next cell after the active one
- Overwrite the
should
command and automatically look up the aliased values - Examples of "be.empty" assertion
- Find and parse the price string
- Find an element with maximum number inside its text
- Check if the loaded number is positive
- Concatenate text extracted from the page while avoiding the pyramid of Doom of callbacks
- stub the
Date.prototype.getTimezoneOffset
method - remove optional child elements before checking sorted prices
- checking a number input value as a number
- paste text into a text area
- pick a random 10 digit number that does not have 0 in front
- collect the values from the DOM using its structure
- element is removed from the DOM vs element hides recipe
- check the parsed JSON HTML attribute
- check the copyright year
- confirm the element's text ends with two decimals
- waiting for the button to be enabled before clicking
- confirm the cursor position in the text area
- verify the phone number string using a strict regular expression
- debug failing cy.get and cy.contains commands
- check that each element is visible
- checking the enabled status of multiple elements
- CSS selector nth-child examples
- clear the input field without race condition with the app
- List item with text tag recipe shows
:has
and:contains
selectors - get and set the attribute value for multiple elements using jQuery
attr
and HTML DOMgetAttribute
methos - checking element's visibility in 3 different ways
- checking the input element is a password input
- confirm the text CSS color
- combine negative with positive assertions
- accessing
data-*
properties via the HTMLdataset
property - lesser known Chai assertions
- compute SHA-256 from element's HTML
- wrap and wait for promises to resolve
- using Menu page object
- use different selectors depending on the Bootstrap version
- confirm the same text on the page in two or more places
- get the sum of numbers avoiding pyramid of Doom
- build-in existence assertion
- cy.contains and regular expressions
- store intermediate values using should callback
- confirm the event handler was triggered just once
- count each number after clicking a button
- checking element overflow
- confirm each element text starts with the given string
- find all table cells that start with "CA" and parse and sum prices.
- remove digits and whitespace from each element's text
- iterate over DOM elements using Cypress and
cypress-map
commands - dispatch custom events
- catch any extra elements appearing between the expected states
- validate email using an input element
- check the number of elements various scenarios
- check the number of children
- CSS selectors
:last-of-type
and:first-of-type
example - cy.within does not retry
- confirm that elements with a
data-
attribute also have thehref
attribute - Use cy.within To Limit The DOM Search
- Check the cards refactoring
- Case-insensitive query recipe
- Handle telephone links like
tel:+1...
- Select hidden or visible elements
- Loading element inside an element and the accidentally passing test
- Attributes vs Properties
- add elements to jQuery subject
- query multiple elements in order
- using the input labels property
- confirm the element is detached
- root element attributes
- Parse Email URL
- Find All Buttons Without
data-cy
attribute - Detect layout shift
- Confirm the element's height does not change
- Confirm the element is vertically centered
Working with the window object
- Checking a dynamic property added to the
window
object - Controlling the window.confirm dialog
- Stub the
window.print
method recipe - Stub the
window.open
method recipe - Testing the
mailto
HREF anchor links - Element with ID property is automatically linked to the
window
object - Testing the
window.close
method - Stub the
window.open
method redux recipe
Selecting an option
- Select value from an
optgroup
element - Select an item by partial text match
- Assert the selected value or multiple values in a
<select>
element - Select an item by id
- Select an invalid option to reach the error-handling case
Testing checkboxes
- Click a single random element or multiple checkboxes
- Find and confirm the list of labels for checked checkboxes
- Check only the enabled checkboxes
- check the first N checkboxes
- check and verify all checkboxes
Working with forms
- Get input element by its label by writing a custom command
- Confirm the values entered in the input elements in a form
- Form input validation
- Set multiple form inputs at once
- jQuery form serializeArray method
- Map input fields to values
- Hide Input Fields Before Taking A Screenshot
- confirm the required attributes
- entering only the required form fields
Cypress secrets
- Conditional testing
- Conditional accept
- Avoid "Mixing async and sync code" by controlling the value the code yields
- use sanity assertions
- wait for the element to be stable
- click in parallel to a Cypress command
Working with network
- Request a specific comment using an ID read from the page
- Simulate Network errors recipe
- Refactor Requested resource not found code into an utility function
- Send synthetic "offline" and "online" events
- Intercept all network calls
Spies and stubs
- confirm the spy was called with the right object
- Stub Geolocation to test error handling
- Stub called with the match
- Stub calls depending on the arguments
- Prepare to spy
Testing tables
- get the table cell using row and column indices
- Confirm the column index
- Update table row with retries
- Table with prices confirms the prices in every table row.
- Check the table has some columns in the expected order
- Find the table row with the exact table cell text
- Find the table row having cells with an attribute
- Select a table cell by the column heading
- read a value from a table cell and enter it into a field
- pick the first table column of the second table
- find the table row index with the given text
- Table has row with randomly picked id
📝 Read the blog post Test HTML Tables Using cy.table Query Command.
Some of the recipes use cypress-map queries to show a better solution to the same exercise.
Courses
I have several Cypress courses at cypress.tips/courses
- I cover the very basics of E2E and Component testing in my free course Cypress Version 10: Fundamentals
- You can fully learn E2E and React Component testing in my hands-on course Testing The Swag Store
- Interested in learning more about
cy.intercept
,cy.request
, and the related commands? Take my Cypress Network Testing Exercises course - Need to step up your tests and take advantages of the many Cypress plugins? Take my course Cypress Plugins that covers 20+ plugins (I wrote most of them)
Videos
Some of the examples and the recipes listed here are explained through short videos I post on my YouTube channel. The playlist Cypress Tips & Tricks has 600+ videos! You can search them all from my page cypress.tips/search.
The newsletter
Every month I write and send a newsletter Cypress Tips & Tricks with a few main news and learning resources. You can subscribe, it is absolutely free.