'Get the value of a rect attribute(fill color) in Testcafe with typescript
I've the following code:
<colored-item label="Label A" symbol-size-left="9.5" symbol-size-right="12" symbol-right="" symbol-left="<svg viewport="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width="24" height="24">
<rect x="0" y="0" width="24" height="24" stroke="black" fill="rgb(0, 91, 142)" stroke-width="0" />
</svg>" small-font="true"></colored-item>
and I need the value of the "fill" attribute("rgb(1, 89, 138)").
I tried the following:
const fillColor = await Selector('colored-item').getAttribute('symbol-left');
The result is:
<svg viewport="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width="24" height="24">
<rect x="0" y="0" width="24" height="24" stroke="black" fill="rgb(1, 89, 138)" stroke-width="0" />
</svg>
When I try
const fillColor = await Selector('colored-item').withAttribute('symbol-left').getAttribute('fill');
the result is "null"
Any ideas how to access the "fill" attribute directly?
Otherwise I need to use regex, right?
Solution 1:[1]
As far as I understand, you put the SVG element in the attribute of the colored-item. But to display this SVG on the page, it should be added to the DOM.
Testcafe tries to search elements by DOM, so it means you should research DOM elements on the page and find out which selector you need to use exactly. According to the information that I see, you can get these attributes directly from rect:
await Selector('rect').getAttribute('fill')
Solution 2:[2]
I finally solved it via regex:
const fillColor = await (Selector('colored-item').getAttribute('symbol-left')).match(/fill="?([\d\w\(\ \,\)]*)"/)[1];
If you want to use it just substitute fill=" with your string expected to exclude and at the end the
"
here
)"/
with your expected end character (or string if needed)
The result will be a match and a group. Just select the group by adding [1] as seen above.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aleksey |
| Solution 2 | Henry Ecker |
