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

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

Related

Attempting to using Selenium Grid to run test with Microsoft Edge, SessionNotCreatedError

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?

Intern/Leadfoot : Getting error - Expecting a function in instanceof check, but got [object Object] on .Click() method

I am learning Intern/leadfoot and trying to write a simple test. The test is logging an user to the site and logging out the user after verification on the next page.
Using Chromedriver v2.21.
Getting unknown error : Expecting a function in instanceof check, but got [object Object] for click() method for an element. However, the element is being identified and get the value for getVisibleText().
Here is my test Code:
define(function (require) {
var registerSuite = require('intern!object');
var assert = require('intern/chai!assert');
registerSuite({
name: 'Acceptance',
'Login': function () {
return this.remote
.get(require.toUrl('http://example.com'))
.setFindTimeout(5000)
.findByXpath('id("ius-userid")')
.click()
.type('user#user.com')
.end()
.findByXpath('id("ius-password")')
.click()
.type('password')
.end()
.findByXpath('id("ius-sign-in-submit-btn")')
.click()
.end()
.sleep(15000)
},
'HomePage': function () {
return this.remote
.setFindTimeout(5000)
.findByXpath('id("userWelcome")')
.getVisibleText()
.then(function (text) {
assert.strictEqual(text, 'Welcome user#user.com!', 'Vaerify that, the Home page for the logged in user is displayed!');
})
.end()
.findByXpath('id("settingsAndLogout")/A[2]')
.getVisibleText()
.then(function(text){
console.log("The Sign out link text is :...", text.trim());
assert.strictEqual(text.trim(), 'Sign Out', 'Verify that, the Sign Out link is present.');
})
.click()
.end()
}
});
});
And, here is the output:
Listening on 0.0.0.0:9000
Tunnel started
? Created session chrome on any platform (5fcd3559690a324e3a5a3db6cd367387)
√ chrome on any platform - Acceptance - Login (20.268s)
The Sign out link text is :... Sign Out
x chrome on any platform - Acceptance - HomePage (0.13s)
UnknownError: [POST http://localhost:4444/wd/hub/session/5fcd3559690a324e3a5a3db
6cd367387/element/0.8815118646376954-2/click] unknown error: Expecting a functio
n in instanceof check, but got [object Object]
(Session info: chrome=49.0.2623.112)
(Driver info: chromedriver=2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7
c4),platform=Windows NT 6.1 SP1 x86_64)
at runRequest <node_modules\leadfoot\Session.js:88:40>
at <node_modules\leadfoot\Session.js:109:39>
at new Promise <node_modules\dojo\Promise.ts:411:3>
at ProxiedSession._post <node_modules\leadfoot\Session.js:63:10>
at Element._post <node_modules\leadfoot\Element.js:23:31>
at Element.click <node_modules\leadfoot\Element.js:138:15>
at Command.<anonymous> <node_modules\leadfoot\Command.js:680:19>
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 Command.target.(anonymous function) [as click] <node_modules\leadfoot\Comm
and.js:674:11>
at Test.registerSuite.IQC_HomePage [as test] <tests\functional\IQC_Acceptance
.js:44:7>
at <node_modules\intern\lib\Test.js:181: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 nextTickCallbackWith0Args <node.js:453:9>
at process._tickCallback <node.js:382:13>
No unit test coverage for chrome on any platform
Need help in figuring out the issue. Thanks in advance!
Here's a suggestion:
.findByXpath('id("settingsAndLogout")/A[2]')
.getVisibleText()
.then(function(text){
console.log("The Sign out link text is :...", text.trim());
assert.strictEqual(text.trim(), 'Sign Out', 'Verify that, the Sign Out link is present.');
})
.end()
.findByXpath('id("settingsAndLogout")/A[2]')
.click()
.end()
Not the most elegant solution as findbyXpath is redundant. But the thing is, .click() expects that previous command/element promise returns actual element when resolved (findByXpath will do that).
Hope this helps!

WebDriverJs' getPageSource gives me an object rather than the page's source

res.json is returning blank when I try display the source of the page. The Selenium log shows that the source code was retrieved. Any idea how I can receive the updated page source properly?
It returns the same thing if I use other functions like get current url.
Code:
var driver = new webdriver.Builder().usingServer('http://localhost:4444/wd/hub').withCapabilities(webdriver.Capabilities.firefox()).build();
driver.get('http://www.google.com');
var source = driver.getPageSource();
console.log(source);
res.json({ message: source });
console.log outputs:
[{ then: [Function: then],
cancel: [Function: cancel],
isPending: [Function: isPending] }
Selenium log:
16:17:30.273 INFO - Executing: [new session: Capabilities [{browserName=firefox}]])
16:17:30.286 INFO - Creating a new session for Capabilities [{browserName=firefox}]
16:17:39.751 INFO - Done: [new session: Capabilities [{browserName=firefox}]]
16:17:39.862 INFO - Executing: [get: http://www.google.com])
16:17:43.828 INFO - Done: [get: http://www.google.com]
16:17:43.863 INFO - Executing: [get page source])
16:17:44.036 INFO - Done: [get page source]
16:17:44.081 INFO - Executing: [delete session: d816aa4f-f5ad-4a59-aec0-4475cab4dff1])
16:17:44.206 INFO - Done: [delete session: d816aa4f-f5ad-4a59-aec0-4475cab4dff1]
source is a promise to get the source, not the source itself. I'd expect you have to do something like:
source.then(function (src) {
res.json({ message: src });
});
The clue there is that when you output source to the console, you get an object that has then, cancel, and isPending methods. The then method is very often used by promise frameworks to pass the callback that will be called when the promise is resolved.

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...)

Error Message : Unable to find element with xpath in phantomsJS

I am using simple NodeJS script for testing google.com. phantomJS browser is used.
var webdriver = require('selenium-webdriver');
var assert = require('assert');
var driver = new webdriver.Builder().
withCapabilities({
browserName : "phantomjs"
}).
usingServer('http://127.0.0.1:4444/wd/hub').build();
//driver.manage().timeouts().implicitlyWait(60000);
driver.get('http://www.google.com');
driver.findElement(webdriver.By.xpath('//*[#id="gbqf"]')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.getTitle().then(function(title) {
assert.equal("webdriver - Google Search", title);
});
driver.quit();
Running the standalone selenium server using
> java -jar selenium-server-standalone-2.35.0.jar
Running the script parallelly using node command.
I am getting the following error
> timers.js:103
> if (!process.listeners('uncaughtException').length) throw e;
> ^ UnknownError: Error Message => 'Unable to find element with xpath
> '//*[#id="gbqf"]'' caused by Request =>
> {"headers":{"Accept":"application/json,
> image/png","Connection":"Keep-Alive","Content-Length":"45","Content-Type":"application/json;
> charset=utf-8","Host":"localhost:17476"},"httpVersion":"1.1","method":"POST","post":"{\"using\":\"xpath\",\"value\":\"//*[#id=\\\"gbqf\\\"]\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/440b8b90-0fc8-11e3-8024-5bdaea20ab82/element"}
> Build info: version: '2.35.0', revision: 'c916b9d', time: '2013-08-12
> 15:42:01' System info: os.name: 'Linux', os.arch: 'i386', os.version:
> '2.6.18-8.el5', java.version: '1.6.0_16' Driver info: driver.version:
Is there a chance the page has not fully loaded as I know that when I go to google.com, it redirects me to my local google.co.uk site.
Strictly for debugging purposes, put a sleep of 5 seconds before the findElement command. If that then works, replace with a webdriverWait until the object appears on screen.
However, I have also noticed that you are sending the keys to the "form" element. Will this work? Do you not want to send keys to the input field?
Assert that you are actually on the URL that you expect to be on prior to calling the findElement command.

Resources