乐闻世界logo
搜索文章和话题

How to select an svg element with title using cypress?

1个答案

1

When using Cypress for testing, if you want to select SVG elements using the title attribute, you can use the cy.get() command with attribute selectors. Here is a practical example. Suppose you have an SVG element containing a title attribute, like this:

html
<svg> <title id="uniqueTitleId">Example SVG</title> <!-- Other SVG content --> </svg>

To select this SVG element, you can use the following Cypress command:

javascript
cy.get('svg title[title="Example SVG"]')

In this example, cy.get() uses a selector string to find matching elements. This selector specifies the element type title and uses bracket syntax [title="Example SVG"] to indicate that the title attribute must match "Example SVG".

However, the above selector assumes the SVG's title is an attribute, not a child element. If the title is actually a child element, you need to select the title tag itself rather than its attribute. In this case, you can select the title tag based on its content:

javascript
cy.get('svg title').contains('Example SVG')

Additionally, if the title tag has a unique ID or other attributes that can uniquely identify it, you can use those attributes to select the element. For example:

javascript
cy.get('svg #uniqueTitleId') // Select by ID
javascript
cy.get('svg [id="uniqueTitleId"]') // Select by attribute selector

Note that when searching for elements within an SVG element, you may need to ensure your selector properly accounts for the SVG namespace. SVG elements and regular HTML elements can behave differently. While Cypress typically handles SVG element selection correctly, additional handling may sometimes be required to accurately select and interact with them.

2024年6月29日 12:07 回复

你的答案