Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - How to create a condition in protractor for when an element exists or not

I'm using Protractor JS. And the site is written in Angular JS.

So I have a toggle switch. And I noticed the value in the toggle switch goes from true to false and false to true when you switch it off or on.

I am trying create a condition when Protractor visits my page when it sees the toggle switch 'off' it will turn it 'on'. If the toggle switch is already 'on', it will first turn it 'off' then turn it 'on' again.

I came up with this code, but for some reason it is not working:

 if( expect(element(By.id('toggle-switch')).element(By.css('[value="false"]')).isDisplayed()) ) {
            element(By.id('toggle-switch')).click();
            console.log('in the if')
       }

       else{
           element(By.id('toggle-switch')).click();
           browser.sleep(3000);
           element(By.id('toggle-switch')).click();
           console.log('in the else')
       }

This code appears to work only for the if statement. For some reason it will never go to the else. Here is the error I'm receiving:

NoSuchElementError: No element found using locator: By.cssSelector("[value="false"]")

So then I tried

.isPresent() instead of .isDisplayed() I don't receive the above error anymore, but for some reason when using .isPresent() it always goes to the if statement and only runs that, and never the else statement. No errors displayed.

If there is a better way please let me know. This seems very limiting to not be able to create proper conditions in this framework.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Remember that isDisplayed() returns a promise, you can try with:

element(anyFinder).isDisplayed().then(function(result) {
    if ( result ) {
        //Whatever if it is true (displayed)
    } else {
        //Whatever if it is false (not displayed)
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...