Attempting to using Selenium Grid to run test with Microsoft Edge, SessionNotCreatedError - node.js

I am currently attempting to setup Selenium Grid using javascript and selenium-webdriver. I have my hub and node setup and currently have run successful tests on Chrome and Firefox. However, I am running into some trouble setting up a test for Microsoft Edge. Just a test that pulls up Google and prints the title.
const { Builder } = require("selenium-webdriver");
const edge = require("selenium-webdriver/edge");
let opts = new edge.Options();
(async function helloSelenium() {
let driver = new Builder()
.usingServer("http://XX.XX.XX.XX:4444/wd/hub")
.forBrowser('edge')
.setEdgeOptions(opts)
.build();
try {
await driver.get('http://www.google.com')
.then(() => driver.getTitle())
.then(title => console.log(title))
}
finally {
await driver.quit();
}
})();
The error I'm getting shows up on the command prompt in the hub (nothing shows up in the node). Showing as follows:
(node:8956) UnhandledPromiseRejectionWarning: SessionNotCreatedError: Unable to create session from {
"desiredCapabilities": {
"browserName": "edge",
"se:CONFIG_UUID": null
},
"capabilities": {
"firstMatch": [
{
"browserName": "edge"
}
]
}
}
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'MDEV', ip: 'XX.XX.XX.XX', os.name: '....', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_291'
Driver info: driver.version: unknown
at Object.checkLegacyResponse (C:\Users\Administrator\Documents\sel-testing\node_modules\selenium-webdriver\lib\error.js:553:15)
at parseHttpResponse (C:\Users\Administrator\Documents\sel-testing\node_modules\selenium-webdriver\lib\http.js:634:13)
at Executor.execute (C:\Users\Administrator\Documents\sel-testing\node_modules\selenium-webdriver\lib\http.js:568:28)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:8956) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
I haven't found much regarding the usage of Microsoft Edge in JS Selenium Grid, so I've come here to ask for help.
Any assistance would be appreciated!
EDIT
I tried using the Node Config as suggested by Yu Zhou, and am now getting a different error: UnhandledPromiseRejectionWarning: SessionNotCreatedError: Unable to create new service: EdgeDriverService
I attempted to use a different function that uses #microsoft/edge-selenium-tools instead of selenium-webdriver like so:
const edge = require("#microsoft/edge-selenium-tools");
let options = new edge.Options().setEdgeChromium(true);
let driver = new edge.Driver().createSession(options);
When run, this does create an Edge session, however I have not found a way to send this to my Selenium Grid. Can someone help me to do so, or offer guidance with the new error on my old code?

Related

NodeJS Javascript - ChromeDriver - Script works fine in Windows. In Docker gives ElementNotFoundException

I have an automation script which is in NodeJS JavaScript which uses chromedriver and selenium-webdriver. It runs perfectly fine in Windows but in Docker container it gives ElementNotFoundException. The chrome version and chromedriver version matches.
Following is the JavaScript file:
require("chromedriver");
const {By,Key,Builder} = require("selenium-webdriver");
const chrome = require('selenium-webdriver/chrome');
async function functionA(){
const url = "abcd.com";
var cCode;
//To wait for browser to build and launch properly
let driver = await new Builder()
.forBrowser("chrome")
.setChromeOptions(new chrome.Options().addArguments(['--no-sandbox','--headless', '--disable-dev-shm-usage']))
.build();
await driver.get(url);
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
await wait(1 * 20 * 1000);
await driver.manage().window().setRect({ width: 1552, height: 840 });
await driver.findElement(By.id("email")).click();
await driver.findElement(By.id("email")).sendKeys("abcd");
var sName = await driver.findElement(By.id("email")).getText();
console.log("sName is: " + sName);
await driver.findElement(By.id("submitbutton")).click();
//this.timeout(1.33 * 20 * 1000);
await wait(1 * 20 * 1000);
//It is always a safe practice to quit the browser after execution
await driver.quit();
//console.log(cCode);
return 'some code;
}
async function testFunctionA()
{
var result = await functionA();
console.log(result);
}
testFunctionA();
Above script is called through a bash script.
#!/bin/bash
v=$(node ./test/executeScript.js)
echo "$v"
This shell script is called through docker:
FROM timbru31/node-chrome
USER root
RUN node --version
RUN npm --version
RUN apt-get update
RUN mkdir /data
COPY . /dataRUN npm --prefix /data install
RUN apt-get install -y apt-utils
RUN google-chrome --product-version
ADD /test /data/test
ADD /load-test /data/load-test
RUN ls -a
RUN SAUTH=$(sh /data/bashScript.sh)
Now when I run this docker file, I get the following exception
(node:8) UnhandledPromiseRejectionWarning: NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":"*[id="emailInput"]"}
(Session info: headless chrome=96.0.4664.93)
at Object.throwDecodedError (/data/node_modules/selenium-webdriver/lib/error.js:517:15)
at parseHttpResponse (/data/node_modules/selenium-webdriver/lib/http.js:643:13)
at Executor.execute (/data/node_modules/selenium-webdriver/lib/http.js:569:28)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async Driver.execute (/data/node_modules/selenium-webdriver/lib/webdriver.js:732:17)
at async toWireValue (/data/node_modules/selenium-webdriver/lib/webdriver.js:140:15)
at async /data/node_modules/selenium-webdriver/lib/webdriver.js:190:16
at async forEachKey (/data/node_modules/selenium-webdriver/lib/webdriver.js:184:9)
at async convertKeys (/data/node_modules/selenium-webdriver/lib/webdriver.js:189:3)
at async Driver.execute (/data/node_modules/selenium-webdriver/lib/webdriver.js:730:22)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:8) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:8) [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.
Command-line options | Node.js v17.2.0 Documentation
Please note that the javascript works perfectly fine in windows. All issues are encountered in docker.
What could be the possible reason and solution to resolve this issue?

What is the Dockerfile to use node:12-alpine with puppeteer#1.19?

Since I faced puppeteer#1.13 error when printing pdf with lots of photos(at least need to renew the lock):
when running in Dev, there was exception:
(node:17) UnhandledPromiseRejectionWarning: Error: Page crashed!
at Page._onTargetCrashed (/usr/src/app/node_modules/puppeteer/lib/Page.js:176:24)
So I would like to use latest version of puppeteer#1.19. However, when I changed to use that, there is error :
Line239: await page.pdf({
path: TEMP_DIR + filename,
format: 'A4',
printBackground: true
});
printPdf() Error
Error: Protocol error (IO.read): Invalid parameters handle: string value expected
at /usr/src/app/node_modules/puppeteer/lib/Connection.js:183:56
at new Promise ()
at CDPSession.send (/usr/src/app/node_modules/puppeteer/lib/Connection.js:182:12)
at Function.readProtocolStream (/usr/src/app/node_modules/puppeteer/lib/helper.js:241:37)
at async Page.pdf (/usr/src/app/node_modules/puppeteer/lib/Page.js:988:12)
at async printPdf (/usr/src/app/puppeteer.js:239:9)
at async /usr/src/app/puppeteer.js:129:21
-- ASYNC --
at Page. (/usr/src/app/node_modules/puppeteer/lib/helper.js:111:15)
at printPdf (/usr/src/app/puppeteer.js:239:20)
at processTicksAndRejections (internal/process/task_queues.js:85:5)
at async /usr/src/app/puppeteer.js:129:21 {
message: 'Protocol error (IO.read): Invalid parameters handle: string value expected'
}
How can I prepare Dockerfile to support puppeteer#1.19 or solve this error? Thanks.

"Unable to find element on closed window" error when finding an element after going to another url

In the test I'm clicking a menu button that go to another page. Afterwards, when I try to find any element on page(The page exists, i can see it), the error 'unable to find element on closed window' keep appearing. I have tried directly getting the url and it works fine. It is when the test clicks a button and goes to another url that I get this error. Can anyone help me to resolve this in intern?
I'm using webdriver IEDriver 32bit, against IE11
Code :
define([
"intern!object",
"intern/chai!assert",
"intern/dojo/node!leadfoot/Element",
"intern/dojo/node!leadfoot/Server",
"intern/dojo/node!leadfoot/helpers/pollUntil",
"intern/dojo/node!leadfoot/keys",
"require",
"tests-config"
], function (registerSuite, assert, Element, Server, pollUntil, keys, require, config) {
registerSuite({
name: 'Test Suite Form Submissions',
'Test Submit Form Step 1': function () {
return this.remote
.get(config.enter_doctor_url)
.setFindTimeout(5000)
.findByXpath("//span[text()='Create Case']")
// goes to another url after clicking
.click()
.end()
// error occurs here
.findByXpath("//*[#id=\"js-wizard-eform\"]/fieldset[1]/table[2]/tbody/tr/td/div[1]/section[1]/label[2]/input")
.pressKeys("John Doe")
.end();
}
});
});
Console Output, Error:
C:\development\xeno1>intern run -w
FAIL: internet explorer 11 on any platform - Test Suite Form Submissions - Test Submit Form Step 1 (6589ms)
NoSuchWindow: [POST http://localhost:44444/wd/hub/session/5aef4686-29ed-40d5-a4e7-bd36982ef034/element / {"using":"xpath","value":"//*[#id=\"js-wiz
ard-eform\"]/fieldset[1]/table[2]/tbody/tr/td/div[1]/section[1]/label[2]/input"}] Unable to find element on closed window (WARNING: The server did not provide
any stacktrace information)
Command duration or timeout: 11 milliseconds
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'workstation', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_111'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{browserAttachTimeout=0, ie.enableFullPageScreenshot=true, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.forceShellWindowsApi=fa
lse, pageLoadStrategy=normal, ignoreZoomSetting=false, ie.fileUploadDialogTimeout=3000, version=11, platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=
false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, browserName=internet explorer, initialBrowserUrl=http://localhost:255
50/, javascriptEnabled=true, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss}]
Session ID: 3111becb-07c3-49cf-a151-e0c32a62a76c
*** Element info: {Using=xpath, value=//*[#id="js-wizard-eform"]/fieldset[1]/table[2]/tbody/tr/td/div[1]/section[1]/label[2]/input}
at runRequest <node_modules\leadfoot\Session.js:92:40>
at <node_modules\leadfoot\Session.js:113:39>
at new Promise <node_modules\dojo\Promise.ts:411:3>
at ProxiedSession._post <node_modules\leadfoot\Session.js:67:10>
at ProxiedSession.find <node_modules\leadfoot\Session.js:1302:15>
at Command.<anonymous> <node_modules\leadfoot\Command.js:42:36>
at <node_modules\dojo\Promise.ts:393:15>
at run <node_modules\dojo\Promise.ts:237:7>
at <node_modules\dojo\nextTick.ts:44:3>
at _combinedTickCallback <internal\process\next_tick.js:67:7>
at Command.find <node_modules\leadfoot\Command.js:23:10>
at Command.prototype.(anonymous function) [as findByXpath] <node_modules\leadfoot\lib\strategies.js:29:16>
at Test Doctor Submit Form Step 1 [as test] <tests\functional\doctor-form-submission.js:44:18>
at <node_modules\intern\lib\Test.js:191:24>
at <node_modules\intern\browser_modules\dojo\Promise.ts:393:15>
at runCallbacks <node_modules\intern\browser_modules\dojo\Promise.ts:11:11>
at <node_modules\intern\browser_modules\dojo\Promise.ts:317:4>
at run <node_modules\intern\browser_modules\dojo\Promise.ts:237:7>
at <node_modules\intern\browser_modules\dojo\nextTick.ts:44:3>
at _combinedTickCallback <internal\process\next_tick.js:67:7>
1/1 tests failed
1/1 tests failed
The documentation does say
findByXpath(path: string): Promise.
Gets the first
element in the currently active window/frame matching the given XPath
selector.
So, if you want to find element in the previous window, you should use switchToWindow to make the window you want to find elements be active

PerfJankie:Error: The environment you requested is not available

I am trying to run PerfJankie(wrapper over Browser-Perf) to measure performance of my app.
perfjankie({
suite: 'X',
url: 'http://localhost:8081',
name: job.component,
run: job.version,
prescript: function (browser) {
browser.driver.manage().window().maximize();
},
time: new Date().getTime(),
callback: function (err, res) {
if (err) {
//console.error(err);
throw err;
}
runQueue(i + 1);
},
repeat: 1,
selenium: 'http://localhost:4444/wd/hub',
couch: COUCH,
browsers: [{ // This can also be a ["chrome", "firefox"] or "chrome,firefox"
browserName: 'chrome',
chromeOptions: {
}
}],
actions: function (browser) {
//some actions
}
});
It gives the following error signature:
C:\Users\...\node_modules\perfjankie\node_modules\q\q.js:155
throw e;
^
Error: [init({"browserName":"chrome","chromeOptions":{"perfLoggingPrefs":{"traceCategorie
s":",blink.console,disabled-by-default-devtools.timeline,benchmark"}},"loggingPr
efs":{"performance":"ALL"}})] The environment you requested was unavailable.
My attempts of isolation:
Expected result: this should launch Chrome and validate my app
Observation: Does not launch chrome
Isolation:
This launches firefox(if I specify browser:firefox) but not chrome
or PhatomJS(chrome is my default browser).
Tried specifying binary path for Chrome(as it was suggested in some link i goggled)
Selenuim version: 2.20.0(Below: 2.34.0- i read some link that showed the issue gets resolved below these versions)
Not sure what am I missing.
P.S. I am not sure what tags to add. If someone could help update right tags, that would be great.
I was having a similar issue, try adding this to the capabilities enablePerformanceLogging: true.
This was related to webdriver-manager installation under node modules. I deleted the entire repo, created a fresh copy and this seems to work.
Also perf jankie does not work with protractor-perf

Selenium + webdriverio - How to retrieve a var produced by the page JS initialisation?

In the acceptance test suite that I'm developing (featuring mocha, sinon and chai at the top of the stack), I am able to load a page in phantomjs and perform all sorts of operations according to the examples available around the web.
The only thing that eludes me is the retrieval of JS variables produced during the startup of the page. I am enclosing a complete example here that shows how the variable app cannot be tested, whereas jQuery can.
The only difference between the two is that app is produced by the run of a $(document).ready(function() {... create var app ...})
The error I get is maximum call stack exceeded (?!?!?!?)
What could I do to perform the check of app when this is available? Maybe something using promises? I can't see all this clearly(**).
Here is the error stack:
19:29:02.918 INFO [14] org.openqa.selenium.remote.server.DriverServlet - Executing: [execute script: return app, []] at URL: /session/73437950-3c14-4392-81ed-c6bd83c3f3fb/execute)
19:29:06.481 WARN [14] org.openqa.selenium.remote.server.DriverServlet - Exception thrown
org.openqa.selenium.WebDriverException: {"errorMessage":"Maximum call stack size exceeded.","request":{"headers":{"Accept":"application/json, image/png","Connection":"Keep-Alive","Content-Length":"33","Content-Type":"application/json; charset=utf-8","Host":"localhost:1693"},"httpVersion":"1.1","method":"POST","post":"{\"args\":[],\"script\":\"return app\"}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/9ca480b0-3c34-11e4-b1c7-0d43d6ab90ff/execute"}}
Command duration or timeout: 3.56 seconds
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:11:15'
System info: host: 'vagrant-xxx-yyyy', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '3.2.0-60-generic', java.version: '1.7.0_65'
Session ID: 9ca480b0-3c34-11e4-b1c7-0d43d6ab90ff
Driver info: org.openqa.selenium.phantomjs.PhantomJSDriver
Capabilities [{platform=LINUX, acceptSslCerts=false, javascriptEnabled=true, browserName=phantomjs, rotatable=false, driverVersion=1.1.0, locationContextEnabled=false, version=1.9.7, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=false, browserConnectionEnabled=false, webStorageEnabled=false, nativeEvents=true, proxy={proxyType=direct}, applicationCacheEnabled=false, driverName=ghostdriver, takesScreenshot=true}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
Here is the test: getTitle, getTagName, getElementSize and execute('return jQuery') succeed; execute('return app')fails.
describe('AAA Test acceptance XXXXX', function(){
var client = {}
before(function(done) {
client = webdriverjs.remote({
desiredCapabilities: {
browserName: 'phantomjs'
},
});
client.init(done) // starts session and opens the browser
});
it('The merchant button',function(done){
client.url('http://www.dev.xxxx.com/api/purchase/index.html')
.getTitle(function(err,title){
expect(err).to.be.null
expect(title).to.have.string('Mobile Payment');
})
.getTagName('.merchant-div',function(err,tagName){
expect(err).to.be.null
expect(tagName).to.be.equal('div')
})
.getElementSize('#ms-input',function(err,size){
expect(err).to.be.null
expect(size.width).to.be.equal(184)
})
.execute('return jQuery', function(err,jquery) {
expect(err).to.be.null
expect(jquery).not.to.be.undefined
expect(jquery).not.to.be.null
})
.execute('return app', function(err,appInstance) {
expect(err).to.be.null
expect(appInstance).not.to.be.undefined
expect(appInstance).not.to.be.null
})
.call(done);
})
after(function(done) {
client.end(done); // ends session and closes the browser
})
});
(**) I already followed the instructions in Selenium WebDriver JS - Explicit Wait, but the error is Object #<WebdriverIO> has no method 'wait' (which makes perfect sense...)

Resources