Gal Ziv
Gal Ziv

Reputation: 7372

protractor - force getText() to resolve since element is removed during the test

I'm writing a test for my angular app. I'm using protractor with jasmine.

The process in the page is as follows: 1) click a button| 2) handler creates a div with content : bar| 3) element(by.id('foo')).getText().then(function(data) { var some-var-i-declared-earlier = data });| 4) click a button which removes this div from DOM| 5) expect assertation for this element value.|

the problem will this promise is resolved the element is not present and thus I get null. if i do expect (which resolves the promise) before I hit the button which removes the div I can see the value I need

the problem is that the flow must remove the div before i do expect.

how can I force the promise to resolve to get it's value? of course any other solution is very welcome.

thanks in advance!

Upvotes: 1

Views: 1361

Answers (1)

hankduan
hankduan

Reputation: 6034

1) click a button| 2) handler creates a div with content : bar| 3) element(by.id('foo')).getText().then(function(data) { var some-var-i-declared-earlier = data });| 4) click a button which removes this div from DOM| 5) expect assertation for this element value.|

element(by...).click(); // step 1
var text = element(by.id('foo')).getText(); // step 3
element(by...).click(); // step 4
expect(text).toEqual('the-right-value'); // step 5

The reason why your original isn't working when you just assign the text data to some-var-i-declared-earlier is because this value is assigned in a promise. This means that by the time you reach the assert statement, the assignment hasn't been done yet (read https://github.com/angular/protractor/blob/master/docs/control-flow.md). In fact, step 1 hasn't even been executed by the time your assertion runs.

Alternatively you can do this (which helps you understand what's going on, but is less concise compared to the first answer):

element(by...).click(); // step 1
var some-var-i-declared-earlier = null;
var text = element(by.id('foo')).getText().then(function(data) {
  some-var-i-declared-earlier = data
}); // step 3
element(by...).click().then(function() { // step 4
  // the fact that this is run inside the 'then' makes sure it executes at the end of step 4
  expect(some-var-i-declared-earlier).toEqual('the-right-value'); // step 5
});

Upvotes: 1

Related Questions