P.T.
P.T.

Reputation: 25177

How to save a locator for objects found via `element.all`?

I've got some code that finds all the "modal-content" divs in a page, and creates some Modal wrapper objects for each element it finds:

var deferred = protractor.promise.defer();
element.all(by.className('modal-content')).then(function(modals) {
  var wrappedModals = [];
  modals.forEach(function(webElementPromise) {
     // the "modal-content" should only be findable for modals
     // that are visible:
     expect(webElementPromise.isPresent()).toBe(true);
     expect(webElementPromise.isDisplayed()).toBe(true);

     wrappedModals.push(new Modal(webElementPromise.locator()));
     console.log(webElementPromise.locator());
  });
  deferred.fulfill(wrappedModals);
});

The problem is that I want to check that these elements have gone away later (after some changes are made on the page). However, the .locator() for each element is identical (just "modal-content"). Is there some other attribute of these objects that I can compute programmatically (something to save so I can ask Protractor to find the object later?)

Note, that if I just save the webElementPromise itself, I get a StaleElementReferenceError: Element is no longer attached to the DOM in the case where the object is gone (which makes sense since the DOM has changed quite a bit). (I'm wary if the reference can go stale for other reasons, so I'm not sure if I should rely on this exception for testing if the element hidden.)

Upvotes: 2

Views: 311

Answers (1)

hankduan
hankduan

Reputation: 6034

You don't need "an identifier to find the elements later again". Your elementFinder/elementArrayFinder are your references to the elements.

var EC = protractor.ExpectedConditions;

var myElems = element.all(by.className('modal-content'));
expect(myElems.count()).toBeGreaterThan(0);
myElems.each(function(elem) {
  // assert that they're all present and visible
  expect(EC.visibilityOf(elem)()).toBeTruthy();
});

// now you do whatever actions that make your elements disappear.

myElems.each(function(elem) {
  // assert that they're all invisible (either not present or not visible)
  expect(EC.visibilityOf(elem)()).toBeFalsy();
});

Upvotes: 1

Related Questions