Cannot catch NoSuchAlertError coming from Protractor when using async/await - selenium

I'm following the new changes happening to Selenium (and Protractor) using the docs here: async-wait.md
So the scenario is that I might have an alert or not so I try and catch NoSuchAlertError. The problem is that the catch is being ignored.
this.closeAlert = async function (acceptAlert) {
try {
var alert = await browser.driver.switchTo().alert();
if (acceptAlert) {
return alert.accept();
}
return alert.dismiss();
} catch (e) {}
};
I'm getting
Failed: no such alert
(Session info: chrome=68.0.3440.106)
(Driver info: chromedriver=2.39.562713 (dd642283e958a93ebf6891600db055f1f1b4f3b2),platform=Mac OS X 10.12.6 x86_64)
NoSuchAlertError: no such alert
(Session info: chrome=68.0.3440.106)
(Driver info: chromedriver=2.39.562713 (dd642283e958a93ebf6891600db055f1f1b4f3b2),platform=Mac OS X 10.12.6 x86_64)
at Object.checkLegacyResponse (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/error.js:546:15)
at parseHttpResponse (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/http.js:509:13)
at doSend.then.response (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/http.js:441:30)
at process._tickCallback (internal/process/next_tick.js:68:7)
From asynchronous test:
Additionally the code works when there is an alert.

It looks like this command isn't awaitable. I tried using your code snippet and intellisense was telling me it didn't have a callable then member.
Here is how I was able to get it to work:
var alert = browser.driver.switchTo().alert()
.catch(e => console.log('caught:', e));
As you can see it worked:

Related

Selenium tests error: WebDriverError: unknown error: net::ERR_CONNECTION

I'm trying to run selenium tests but I get this error:
Error: WebDriverError: unknown error: net::ERR_CONNECTION_REFUSED
(Session info: chrome=98.0.4758.102)
(Driver info: chromedriver=98.0.4758.80 (7f0488e8ba0d8e019187c6325a16c29d9b7f4989-refs/branch-heads/4758#{#972}),platform=Windows NT 10.0.19042 x86_64)
...
From: Task: WebDriver.navigate().to(https://localhost:4200/asd)
I tried to update webdriver but still not working. I really know what to do because I'm really new to Protractor etc. How can I solve this issue?
It looks like you are trying to send the browser to https://localhost:4200/asd. This is a URL that is passed to selenium. If you use Selenium Grid make sure that the URL can be reached from there. This especially means no localhost or 127.0.0.1 URLs, as they resolve to the selenium-grid-host.
If you need to detect the local network-IP you can try a variation of (node.js)
var address,
ifaces = require("os").networkInterfaces();
for (const dev in ifaces) {
ifaces[dev].forEach((details) => {
if (details.family === "IPv4" && details.internal === false) {
address = details.address;
}
});
}
and build the URLs with the detected address.

Appium Unknown server-side error occurred - did not start application

I am trying to test a mobile app in appium but its throwing the following error
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command.
Original error: Cannot start the 'com.example.abc' application.
Original error: 'com.example.abc.ui.splash.SplashActivity' or 'com.example.abc.ui.splash.SplashActivity' never started.
Visit https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/android/activity-startup.md for troubleshooting
(WARNING: The server did not provide any stacktrace information)
Follwing are my capabilities setup
#Before
public void setUp() {
File f = new File( "src" );
//App Name
File fs = new File( f, "app-sandbox-debug.apk" );
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability( "deviceName", "Samsung SM-A305F/DS Android 10, API 29" );
capabilities.setCapability( "platformName", "Android" );
capabilities.setCapability( CapabilityType.BROWSER_NAME, "Android" );
capabilities.setCapability("normalizeTagNames","true");
capabilities.setCapability( MobileCapabilityType.APP, fs.getAbsolutePath() );
try {
driver = new AndroidDriver<MobileElement>( new URL( "http://127.0.0.1:4723/wd/hub" ), capabilities );
driver.manage().timeouts().implicitlyWait( 1000, TimeUnit.SECONDS );
System.out.println("Application running");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
I am unable to find the error cause nor unable to find what's missing at my end.
You can use adb shell dumpsys window windows command to see the launch activity
Launch the app on the device
connect the device to PC/Laptop with adb enabled
In terminal enter the following command adb shell "dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'"
Use the correct activity which can be launched properly

WebDriverException: target frame detached while interacting with elements within iframe using ChromeDriver Chrome and Selenium

I use Chromedriver 78.0.3904.70,
WebDriverException: target frame detached exception
has occurred, but in previous version of chromedriver all worked fine.
Now in my iFrame I can't find any elements during the autotest, where should be another iFrame, but i can do it by hand.
Also switching to iFrame doing successfully during autotest. I think may be there is a bug in new chromedriver? Any ideas?
org.openqa.selenium.WebDriverException: target frame detached
(Session info: chrome=78.0.3904.97)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'PDF323-440G4', ip: '172.16.14.147', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_181'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 78.0.3904.97, chrome: {chromedriverVersion: 78.0.3904.70 (edb9c9f3de024..., userDataDir: C:\Users\Nikolay\AppData\Lo...}, goog:chromeOptions: {debuggerAddress: localhost:64307}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: c6f28448e742438746371ee017a51dda
This error message...
WebDriverException: target frame detached
...implies that for a certain HttpRequest the resultant HttpServerResponseInfo was net::HTTP_NOT_FOUND.
Details
As per the discussion Some error codes are not standard compliant there were some error codes returned by the ChromeDriver which were not compliant to the W3C standard. They were replaced with the corresponding standard error codes:
asynchronous script timeout -> script timeout
element not visible -> element not interactable
no such session -> invalid session id
session not created exception -> session not created
xpath lookup error -> invalid selector
Additionally, there are some Chrome-specific error codes which still exists and most clients will treat them as unknown error. These error codes are:
chrome not reachable
disconnected
forbidden
no such execution context
tab crashed
target frame detached
This issue was addressed through the bug / commit and the current status is ToBeReleased.
Deep Dive
The error target frame detached is the outcome of case kTargetDetached where case kTargetDetached is defined in http_handler.cc and occurs when the HttpServerResponseInfo contains HTTP_NOT_FOUND as follows:
void HttpHandler::HandleCommand(
const net::HttpServerRequestInfo& request,
const std::string& trimmed_path,
const HttpResponseSenderFunc& send_response_func) {
base::DictionaryValue params;
std::string session_id;
CommandMap::const_iterator iter = command_map_->begin();
while (true) {
if (iter == command_map_->end()) {
if (w3cMode(session_id, session_thread_map_)) {
PrepareResponse(
trimmed_path, send_response_func,
Status(kUnknownCommand, "unknown command: " + trimmed_path),
nullptr, session_id, true);
} else {
std::unique_ptr<net::HttpServerResponseInfo> response(
new net::HttpServerResponseInfo(net::HTTP_NOT_FOUND));
response->SetBody("unknown command: " + trimmed_path, "text/plain");
send_response_func.Run(std::move(response));
}
return;
}
if (internal::MatchesCommand(
request.method, trimmed_path, *iter, &session_id, &params)) {
break;
}
++iter;
}
and most possibly the reason in your case is kTargetDetached:
case kTargetDetached:
response.reset(new net::HttpServerResponseInfo(net::HTTP_NOT_FOUND));
break;
I was also facing the same issue on Version 79. Updated to chrome Version 80.0.3987.53 (Official Build) beta (64-bit) on my mac machine and used chromedriver version 80.0.3987.16 while working with selenium. Switching to iframe is working fine now.
Got a hint from the above point that it has been fixed in version 80. Hope it helps!
As a workaround, we can use a try and catch block for the elements in which this error occurs - and the tests will continue further without stopping
try {
button.click();
} catch (WebDriverException e) {
e.printStackTrace();
}
May not be correct or optimal solution but after adding Thread.sleep and nested try catch block issue got resolved.
Note: in WebDriverException I tried the same element again
try
{
Thread.sleep(1000);
yourWebelement.click();
}
catch(WebDriverException e)
{
yourWebelement.click();
}
catch(Exception ee)
{
ee.printStackTrace();
throw ee;
}
Worked for me:
driver.switchTo().parentFrame();
I had the same issue when my Selenium driver version mismatched the version of my Chrome browser because I updated my web browser to its last version without updating also the Selenium driver.
I fixed the issue by updating also my selenium web driver to match the updated chrome.
I found that I get this error when I have too many instances of ChromeDriver running.
I have an application that attempts to shut down instances of ChromeDriver when I am done with current tests, but when I see this error, I usually find that I have 10-20 instances running because I was debugging some issue, and not letting the clean-up code run.
Open Task Manager and kill old instances!

Unable to find an web element with JavaScript Selenium Webdriver

I'm trying to run a simple test with selenium without success.
I have a javascript config test:
chrome.config.js
var driver = new webdriver.Builder().
.forBrowser('chrome')
.build();
driver.get('http://www.google.com');
driver.findElement(By.name('btnI')).click();
I'm getting the following error:
(node:5921) UnhandledPromiseRejectionWarning: WebDriverError: element not interactable
(Session info: chrome=70.0.3538.77)
(Driver info: chromedriver=2.44.609551 (5d576e9a44fe4c5b6a07e568f1ebc753f1214634),platform=Linux 4.15.0-42-generic x86_64)
at Object.checkLegacyResponse (/home/pablo/workspace/bricks-editor/node_modules/selenium-webdriver/lib/error.js:585:15)
at parseHttpResponse (/home/pablo/workspace/bricks-editor/node_modules/selenium-webdriver/lib/http.js:533:13)
at Executor.execute (/home/pablo/workspace/bricks-editor/node_modules/selenium-webdriver/lib/http.js:468:26)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:5921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5921) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
What can be wrong here?
My settings:
node version: 8.11.3
chromedriver version: 2.44.609551
OS: Ubuntu 18.0.4 LTS 64 bits
After some tests, I was able to do my code work with the following changes.
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
var driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
driver.get('http://www.google.com');
var btnI;
driver.findElements(By.name('btnI')).then(function(list) {
btnI = list[1];
btnI.click();
});
There are two input fields with the same #name: the first one is hidden. You need to handle the second (visible) one:
driver.findElement(By.cssSelector('div.FPdoLc input[name="btnI"]')).click();

Selenium with PHPUnit not loading page

I am trying to make a test suit for a php project using phpunit and phpunit-selenium. In my composer file I have
"require-dev": {
"phpunit/phpunit": "^5.7",
"phpunit/phpunit-selenium": "^3.0"
}
The installed phpunit version is 5.7.4
I am using selenium-server-standalone-3.0.1.jar as the selenium server. I start the server with
java -Dwebdriver.gecko.driver="C:\Harlan\Selenium\geckodriver.exe" -jar selenium-server-standalone-3.0.1.jar
In my test class I have
require_once dirname(__FILE__) . '/../../vendor/autoload.php';
class UserSubscriptionTest extends PHPUnit_Extensions_Selenium2TestCase {
public function setUp() {
$this->setHost('localhost');
$this->setPort(4444);
$this->setBrowserUrl('http://localhost/cwckids/web/user/login');
$this->setBrowser('firefox');
}
public function tearDown() {
$this->stop();
}
public function testFormSubmissionWithUsername()
{
$this->byName('login-form[login]')->value('admin');
$this->byName('login-form[password]')->value('mypassword');
$this->byId('login-form')->submit();
$content = $this->byTag('body')->text();
$this->assertEquals('Everything is Good!', $content, 'something wrong!!');
}
}
My problem is that the firefox browser opens up but doesn't load the page http://localhost/cwckids/web/user/login
The test fails immediately because it cannot find the elements. It give a message saying
Unable to locate element: {"method":"name","selector":"login-form[login]"}
I couldn't find a solution for the problem. Is it some version incompatibility? I tried with a few versions of Firefox and also selenium server. My Firefox version is 50.1.0. If it is a version incompatibility can someone suggest correct versions? Thanks
The complete trace
C:\xampp\htdocs\seleniumtest>phpunit tests/acceptance/UserSubscriptionTest.php
PHPUnit 5.7.4 by Sebastian Bergmann and contributors.
E 1 / 1 (100%)
Time: 6.51 seconds, Memory: 9.25MB
There was 1 error:
1) UserSubscriptionTest::testFormSubmissionWithUsername
PHPUnit_Extensions_Selenium2TestCase_WebDriverException: Unable to locate element: {"method":"name","selector":"login-form[login]"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'DESKTOP-I0LAEAM', ip: '192.168.8.101', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_77'
Driver info: driver.version: unknown
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase\Driver.php:165
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase\CommandsHolder.php:108
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase\Element\Accessor.php:134
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase\Element\Accessor.php:175
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase\Element\Accessor.php:108
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase.php:394
C:\xampp\htdocs\seleniumtest\tests\acceptance\UserSubscriptionTest.php:66
C:\xampp\htdocs\seleniumtest\tests\acceptance\UserSubscriptionTest.php:66
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase.php:348
C:\xampp\htdocs\seleniumtest\vendor\phpunit\phpunit-selenium\PHPUnit\Extensions\Selenium2TestCase.php:314
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.
There's a few things I'd suggest changing:
You are missing a call to $this->url(); from, what I can see within your test method:
public function testFormSubmissionWithUsername()
{
$this->url('your actual URL here'); // Add this line
$this->byName('login-form[login]')->value('admin');
$this->byName('login-form[password]')->value('mypassword');
$this->byId('login-form')->submit();
$content = $this->byTag('body')->text();
$this->assertEquals('Everything is Good!', $content, 'something wrong!!');
}
You are also not calling the parent::setUp() method from within your own setUp method:
protected function setUp()
{
parent::setUp();
// Set your browser, port setup etc here
}
There's also no need to explicitly call $this->stop(); from within tearDown, so remove that function completely.
Lastly, I'd tell selenium to take screenshots of failures, they save a lot of time:
/**
* Override this method from \PHPUnit_Framework_TestCase so we can capture a screenshot.
*
* #return void
*/
public function onNotSuccessfulTest($exception)
{
$filedata = $this->currentScreenshot();
$file = YOUR_SCREENSHOT_DIR . '\testfails\\' . basename(get_class($this)) . '.png';
file_put_contents($file, $filedata);
parent::onNotSuccessfulTest($exception);
}