Search code examples
javascriptseleniumrobotframework

Validate Execute Javascript result


i'm trying to validate the element color so i can click on it or pass for the next step but my variable ${tech_color} are returning None as a result.

Click Tech
    FOR  ${ITEM}  IN RANGE    0    10
        Wait Until Element Is Visible    ${pageOnboarding.Tech}
        ${tech_color}=     Execute JavaScript     matchingElement = document.evaluate("//div[@role='button'][text()='Tech']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; window.getComputedStyle(matchingElement).color;
        Log To Console   ${tech_color}
        Run Keyword If  ${tech_color} !='rgb(239, 17, 61)'   Click Element   ${pageOnboarding.Tech}
        Exit For Loop If    ${tech_color} == 'rgb(239, 17, 61)'
    END

This is the log I have in my console when execute my test:

Onboarding
DevTools listening on ws://127.0.0.1:53497/devtools/browser/51b0864a-ee9f-4000-9795-ea671ee5dfbf
Onboarding                                                         .None   
None
None
None
None
None
None
None
None
Onboarding                                                 | FAIL |

Executing the same javascript code in Opera console:

Item not selected:

matchingElement = document.evaluate("//div[@role='button'][text()='Tech']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; window.getComputedStyle(matchingElement).color;
'rgb(0, 0, 0)'

Item selected:

matchingElement = document.evaluate("//div[@role='button'][text()='Tech']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; window.getComputedStyle(matchingElement).color;
'rgb(239, 17, 61)'

I need this validation because the item can be already selected and if i click on it will deselect the item.

I tried using Execute Async JavaScript instead of Execute JavaScript but my test failed because of script timeout.

I also tried converting the rgb value to hex but the function i found didn't work.

P.S: Sorry for the possibles mispelling mistakes.


Solution

  • Please change your javascript code like below and you missed return. Only when you return, you will get the value. I just modified your js code, so please try.

     ${tech_color}=     Execute Javascript        return window.getComputedStyle(document.evaluate("//div[@role='button'][text()='Tech']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue).color;
    

    I tried with sample element and output is in below screenshot enter image description here