GarfieldKlon
GarfieldKlon

Reputation: 12140

Protractor, do I have to use then() after protractor calls?

Is it ok to write:

getFieldX().clear().sendKeys('abc');

or should I write:

getFieldX().clear().then( () => sendKeys('abc));

I'm totally confused about the Promise handling in protractor. clear() returns a promise, so I should use .then() afterwards, shouldn't I?

But I found examples with .then and some without. Protractor itself has an example without .then(): https://www.protractortest.org/#/control-flow

Does Protractor has its own mechanism and resolves one after the other promise so there is no need for using .then() after a protractor call that returns a Promise?

And is the control flow of protractor only active in a spec? When using .sendKeys() in a normal function I have to use .sendKeys().then(...) ?

Upvotes: 1

Views: 94

Answers (1)

Ben Mohorc
Ben Mohorc

Reputation: 694

This all depends on if you are using SELENIUM_PROMISE_MANAGER or not. As this is (has?) becoming deprecated, I would not use it. It should be set to false by default, but if you want to be sure you can add SELENIUM_PROMISE_MANAGER = false; to your conf file. The way that protractor has been moving is to use async/await, so your sendKeys function would look like:

let field = element(by.css('CSS.Selector'));
await field.clear();
await field.sendKeys('abc');

Because these are async functions, you will need to define your function properly, so a basic spec would look like:

describe('Demonstrating async/await',function(){
  it('Should send some keys', async function(){
    let field = element(by.css('CSS.Selector'));
    await field.clear();
    await field.sendKeys('abc');
  });
});

The important difference there is that a function needs to be defined as async function(). As far as reading the code goes, await simply can be read as "Wait until promise resolved to move on". It does get a bit tedious and you feel like you write await before every line of code (you basically do), but I find it significantly better than .then() trees.

Upvotes: 1

Related Questions