What is the difference between get and contain in Cypress?
Hey Ana,
Both Cypress methods provide the same functionality, but there are some distinct features between these functions.
-
get: The get command retrieves DOM elements that match a specific selector. It returns a jQuery object containing the matched elements.
-
contains: The contains command finds elements that contain specific text. It is often used in conjunction with get-to-find elements based on both their selector and their text content.
To learn more about other methods on Cypress, follow this guide on how to check if an element exists in Cypress.
In Cypress, get
and contains
are both powerful commands for querying the DOM, but they serve distinct purposes. The get
command is primarily used to retrieve elements by their selectors, such as IDs, classes, or attributes, and it returns a jQuery object containing all elements that match this criteria. On the other hand, contains
looks for elements that include a specific piece of text, making it invaluable when the selector alone might not be specific enough. It’s particularly useful in cases where you need to interact with elements like buttons or links, which are identified more by their text content than their HTML structure.
Building on Madhurima’s explanation, it’s important to note how these commands can be combined for more effective tests. While get
retrieves elements based on CSS selectors, contains
can refine this selection by adding a text-based filter. For instance, if you use get
to select all buttons but only want to interact with one that says ‘Submit,’ contains
can be chained to get
to precisely target that. This approach enhances test accuracy and readability, making your scripts more maintainable and easier to understand.
Expanding further, while both get
and contains
are crucial, understanding their return behavior and how they integrate with Cypress’s retry-ability is key for advanced testing strategies. Get
will continuously retry finding elements until they exist in the DOM or a timeout is reached, making it robust for dealing with elements that might take time to appear due to, say, network responses. Contains
, however, not only retries based on element presence but also checks if the text is present in the element at the moment of execution. This dual-layer check enhances test reliability, particularly in dynamic applications where text and content can change based on user interactions or incoming data.