How do I properly dismiss an alert in JavaScript with Selenium Webdriver?
I am using Cucumber.js and Selenium Webdriver on Node.js.
I am testing a page that has an alert pop-up when the page loads – it asks for permission to use the user’s location which I have disabled in Firefox, so an alert appears advising the user that a default location will be used.
The problem I am having is that although I seem to (visually) be able to dismiss the alert all successive test steps have the error:
UnexpectedAlertOpenError: Dismissed user prompt dialog: Some alert text...
Try as I might I cannot figure out how to get rid of this. I have tried:
Setting an option when I build the browser:
let options = new firefox.Options();
options.setAlertBehavior(UserPromptHandeler, 'dismiss');
options.setPreference('geo.enabled', false);
this.driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
Dismissing it in a Cucumber step:
When('I dismiss the alert', async function() {
this.driver.switchTo().alert().then((alert) => alert.dismiss());
});
And this way (as per Selenium docs):
When('I dismiss the alert', async function() {
await this.driver.wait(until.alertIsPresent());
let alert = await this.driver.switchTo().alert();
await alert.dismiss();
});
I’ve also tried waiting before dismissing:
When('I dismiss the alert', async function() {
await this.driver.manage().setTimeouts({ implicit: 3000 });
this.driver.switchTo().alert().then((alert) => alert.dismiss());
});
And
When('I dismiss the alert', async function() {
await this.driver.sleep(3000);
this.driver.switchTo().alert().then((alert) => alert.dismiss());
});
But the issue remains.
Would anyone know what I’m doing wrong and how to solve this?
My full code:
const { When, Then, Given } = require('@cucumber/cucumber');
const { Builder, By, until, Key } = require('selenium-webdriver');
const { Options } = require('selenium-webdriver/firefox');
const firefox = require('selenium-webdriver/firefox');
const { UserPromptHandeler } = require('selenium-webdriver/lib/capabilities');
Given('I am on the branch locator page', async function () {
let options = new firefox.Options();
//options.setAlertBehavior(UserPromptHandeler, 'dismiss');
options.setPreference('geo.enabled', false);
this.driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
this.driver.wait(until.elementLocated(By.tagName('h1')));
await this.driver.get('https://www.awebsite.com');
});
When('I dismiss the alert', async function() {
await this.driver.sleep(3000);
this.driver.switchTo().alert().then((alert) => alert.dismiss());
});
Then('I click the radio button', async function() {
await this.driver.findElement(By.id('option2')).click();
});
Read more here: Source link
