Robot framework, how to check class
Solution 1
You could create a new keyword via XPath selectors:
Element should have class
[Arguments] ${element} ${className}
Wait until page contains element ${element}[contains(@class, '${className}')]
Or via CSS selectors:
Element should have class
[Arguments] ${element} ${className}
Wait until page contains element ${element}.${className}
Wait until page contains element
could be replaced by any keyword of your liking to check if the element exists and is visible, such as Element should be visible
.
Solution 2
Here's an alternative solution (though the accepted answer's CSS one is quite good), working for any kind of selector strategy:
Element should have class
[Arguments] ${locator} ${target value}
${class}= Get Element Attribute ${locator}@class
Should Contain ${class} ${target value}
It can be modified for any other attribute - just substitute the @class
in Get Element Attribute
with it (or even, make it an optional argument).
Solution 3
Some of the solutions on this page may suffer from sub-string matches. Checking that the class attribute (e.g. test-run
) contains a class (e.g. test
) may pass even though it should fail.
There are a few ways to deal with this, but in the end, I did the following:
Element Should Have Class
[Arguments] ${locator} ${class}
${escaped}= Regexp Escape ${class}
${classes}= Get Element Attribute ${locator} class
Should Match Regexp ${classes} \\b${escaped}\\b
Element Should Not Have Class
[Arguments] ${locator} ${class}
${escaped}= Regexp Escape ${class}
${classes}= Get Element Attribute ${locator} class
Should Not Match Regexp ${classes} \\b${escaped}\\b
Tuomas Toivonen
Updated on June 13, 2022Comments
-
Tuomas Toivonen about 2 years
Is there a keyword in Robot Framework to ensure element has a certain class? Something like
Element should has class element className
Alternatively, I could check if element has a certain attribute with certain value. Former would be more suitable though, as element may contain multiple classes.