How to check if element is present using Selenium with Javascript?

I am struggling with a simple test using Jest and Selenium. I am testing if an element is removed from DOM after clicking on it.

I have tried this:

 test('User removes button after clicking on it', async (done) => {
    await driver.navigate().to('myProjectUrl');
    await driver.wait(until.elementLocated(By.css('.wrapper')), 10000);
    await driver.findElement(By.id('buttonId')).click();
    const deleteButton = await driver.findElement(By.id('buttonId'));
    expect(deleteButton.isDisplayed()).not.toEqual(true);
    done();
});

This seems to work. Test passes but I am getting:

StaleElementReferenceError: stale element reference: element is not attached to the page document

I have also tried this approach:

test('User removes button after clicking on it', async (done) => {
    await driver.navigate().to('myProjectUrl');
    await driver.wait(until.elementLocated(By.css('.wrapper')), 10000);
    await driver.findElement(By.id('buttonId')).click();
    const buttonOrMessage = await driver.wait(until.elementLocated(By.id('buttonId)), 300, 'missing_button');
    expect(buttonOrMessage).toEqual('missing_button');
    done();
});

This approach is returning error, not message as expected.

Any suggestions about what am I missing? Your help would be appreciated.

Upvotes: 2

Views: 3211

Answers (2)

Florent B.
Florent B.

Reputation: 42528

Use until.stalenessOf to wait for the button to be removed from the DOM:

test('User removes button after clicking on it', async (done) => {
  await driver.navigate().to('myProjectUrl');
  let deleteButton = await driver.wait(until.elementLocated(By.css('.wrapper #buttonId')), 10000);
  await deleteButton.click();
  await driver.wait(until.stalenessOf(deleteButton), 300, 'button still present in the DOM');
  done();
});

Upvotes: 1

Marcel
Marcel

Reputation: 1463

If you deleted the deleteButton element it's no longer available / present, so .isDisplayed() throwing a StaleElementReferenceError is expected.

You can re-search for the id 'buttonId' in a try / catch block catching any exceptions and base your assertion on that.

Something like:

let buttonIsStillThere;
try {
    buttonIsStillThere = driver.findElement(By.id('buttonId')).isDisplayed();
} catch () {
    buttonIsStillThere = false;
}

Upvotes: 1

Related Questions