Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protractor, when should I use then() after a click()

I'm running an Angular app and when testing on protractor a click(), I don't know when should I resolve the promise with a then().

I found this on Protractor API:

A promise that will be resolved when the click command has completed.

So, should I use click().then() in every click?

like image 721
Joao Falcao Avatar asked Oct 30 '15 17:10

Joao Falcao


People also ask

What is the use of then function in Protractor?

Protractor has an internal mechanism to wait for such objects automatically but to trigger that mechanism it requires you to use the keyword "then". Any statement started with then keyword, protractors guarantees that operation will perform based on the previous action only.

How do you wait for page to load in Protractor?

Timeout While Waiting For The Page To Load While performing Selenium test automation to navigate a page on the browser, you'll instruct the Selenium WebDriver to load the web page using the browser. get() command. Under the hood, the Protractor framework waits for the page to load completely.


1 Answers

So, should I use click().then() in every click?

Definitely not.

It's not needed because Protractor/WebDriverJS has this mechanism called "Control Flow" which is basically a queue of promises that need to be resolved:

WebDriverJS maintains a queue of pending promises, called the control flow, to keep execution organized.

and Protractor waits for Angular naturally and out-of-the-box:

You no longer need to add waits and sleeps to your test. Protractor can automatically execute the next step in your test the moment the webpage finishes pending tasks, so you don’t have to worry about waiting for your test and webpage to sync.

Which leads to a quite straight-forward testing code:

var elementToBePresent = element(by.css(".anotherelementclass")).isPresent();

expect(elementToBePresent.isPresent()).toBe(false);
element(by.css("#mybutton")).click();
expect(elementToBePresent.isPresent()).toBe(true);

Sometimes though, if you experience synchronization/timing issues, or your app under test is non-Angular, you may solve it by resolving the click() explicitly with then() and continue inside the click callback:

expect(elementToBePresent.isPresent()).toBe(false);
element(by.css("#mybutton")).click().then(function () {
    expect(elementToBePresent.isPresent()).toBe(true);
});

There are also Explicit Waits to the rescue in these cases, but it's not relevant here.

like image 124
alecxe Avatar answered Oct 14 '22 23:10

alecxe