0

I have several test specs and it blocks. One of them :

  it('Add button should exist', async () => {
    var add = $('[test-id="add"]');
    browser.wait(EC.presenceOf(add), 10372);
    expect(await add.isPresent()).toBeTruthy();
  });

I am checking DOM element in this code block. When I run only this it block, test passed successfully. But, when I run all test specs ,I get a error :

message='Unhandled promise rejection: StaleElementReferenceError: stale element reference: element is not attached to the page document|

I am using protactor and selenium web driver. Also I tried related issues : issue1 issue2

I need a help pls.

Aslı
  • 105
  • 1
  • 1
  • 9
  • all methods of browser return promises, thus you should add `await` to handle it so you have `await browser.wait(EC.presenceOf(add), 10372);` otherwise it doesn't do anything – Sergey Pleshakov Nov 18 '19 at 18:13

2 Answers2

0

The message says that element is not attached to DOM. You should first wait for element to be visible and then interact with it:

it('Add button should exist', async () => {
browser.wait(EC.presenceOf($('[test-id="add"]'), 10372);
var add = $('[test-id="add"]');  
expect(await add.isPresent()).toBeTruthy();

});

Sanja Paskova
  • 1,110
  • 8
  • 15
0

First you have to understand what Stale Element Reference Error is. From Mozilla...

The stale element reference error is a WebDriver error that occurs because the referenced web element is no longer attached to the DOM. ... When an element is no longer attached to the DOM, i.e. it has been removed from the document or the document has changed, it is said to be stale

... meaning that when you first interacted with the element, it was tagged as present, but the next time that you intended to use that element it's already gone but is still tagged as present, leading to the error that you are now encountering.

In your code for example,

  it('Add button should exist', async () => {
    var add = $('[test-id="add"]');
    browser.wait(EC.presenceOf(add), 10372);
    // Code continues because the element 'add' is present.
    expect(await add.isPresent()).toBeTruthy(); // Stale error is thrown here when the saved element 'add' is not present anymore.
  });

To fix it, simply re-look for the element directly instead of referencing it from one instance.

  it('Add button should exist', async () => {
   browser.wait(EC.presenceOf($('[test-id="add"]')), 10372);
   expect(await $('[test-id="add"]').isPresent()).toBeTruthy();
  });

Even then, what you're doing here is like expect(true).toBeTruthy(); since the Expected Conditions have already passed for the presence of the element.

Community
  • 1
  • 1
Rudreshuar
  • 125
  • 6