I am trying to run assertion for testing with selenium webdriver through node js but it says undefined, I get the page title which is URL of the page then assert it, looks like I have to import sth for assertion, please help, also please tell me if selenium works fine with node js here is my code:
var webdriver = require('selenium-webdriver'),
//var test = require('selenium-webdriver/testing'),
nodeThen = require('node-then');
var assert = require('assert');
//var jsdom = require("jsdom");
//var document = require('jquery');
var xpath = require('xpath');
//var driver = new webdriver.Builder().
// withCapabilities(webdriver.Capabilities.chrome()).
//build();
function createDriver() {
var driver = new webdriver.Builder()
.usingServer('link')
.withCapabilities(webdriver.Capabilities.chrome())
.build();
driver.manage().timeouts().setScriptTimeout(10000);
return driver;
}
var driver = createDriver();
var By = webdriver.By;
driver.get("URL")
.then(function(){
driver.sleep(10000);
var element=driver.findElement(By.id("get-started"));
element.click();
})
.then(function(){`enter code here`
return driver.getTitle();
})
.then(function(title) {
//console.log(title);
//driver.manage().timeouts().setScriptTimeout(50000);
if (title == ('URL')) {
console.log("pass");
}
//
I was searching for the same issue and I found this snippet which is working for me
driver.findElement(By.id('elementId'))
.getText().then(textValue => {
assert.equal('tested string', textValue);
});
I found it in the examples files of selenium-webdriver's github repo
Did you install asserts? The command would be npm install asserts. Also, you need var Asserts = require('asserts');
This is the example you are looking for
// Require chai.js expect module for assertions
const chai = require('chai');
const expect = require('chai').expect;
// Application Server
const serverUri = '0.0.0.0:3000';
// Official selenium webdriver testing setup
const webdriver = require('selenium-webdriver');
describe('basic test', function () {
let driver;
before(() => {
// Start of test use this
driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
console.log("Selenium Webdriver Chrome Started");
});
after(function(){
// End of test use this.
driver.quit();
});
it('should be on correct page', function (done) {
this.timeout(10000);
driver.get(serverUri);
driver.getTitle().then(function(title) {
expect(title).to.equal('Some String Here');
done();
console.log("Selenium Webdriver Chrome Shutdown");
})
});
});
Related
I want to know how to control the browser that has been opened? I’ve read the API docs, but I can't find the way to do it.
like java
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("debuggerAddress", "127.0.0.1:9222");
WebDriver driver = new ChromeDriver(options);
or python
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
But how to do this by nodejs (javascript) ???
I’m so confused
Taken from https://medium.com/dailyjs/how-to-setup-selenium-on-node-environment-ee33023da72d
The script below will open a chrome browser, input a term, submit the
form, and return the page title. If the test is successful, then it
should print out Test passed
const webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
const driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
driver.get('http://www.google.com').then(function(){
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver\n').then(function(){
driver.getTitle().then(function(title) {
console.log(title)
if(title === 'webdriver - Google Search') {
console.log('Test passed');
} else {
console.log('Test failed');
}
driver.quit();
});
});
});
The below step will help you :
require('chromedriver');
var webdriver = require('selenium-webdriver');
var chrome = require("selenium-webdriver/chrome");
var chrome = require("selenium-webdriver/chrome");
var options = new chrome.Options();
options.options_["debuggerAddress"] = "127.0.0.1:9222";
var driver = new webdriver.Builder()
.forBrowser('chrome')
.setChromeOptions(options)
.build();
driver.get("https://www.google.com")
I am creating a Selenium test for a web page that I am working on and I am getting stuck trying to use the dragAndDrop action. I need to use this action to re-order a wait list that I have. I am new when it comes to Selenium and i'm not sure if I am using correct syntax for the dragAndDrop action. I would appreciate it if someone could help lead me in the right direction. Below is my current code minus some other test I wrote.
const webdriver = require('selenium-webdriver');
const keys = webdriver.Key;
const chromedriver = require('chromedriver');
const chrome = require('selenium-webdriver/chrome');
const rp = require('request-promise');
const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();
const WebElement = require('selenium-webdriver');
const actions = require('selenium-webdriver/lib/input');
driver = new webdriver.Builder().forBrowser('chrome').build();
describe('This is for testing the Rewards Portal using Selenium', function() {
this.timeout(60000);
it('Should reorder the customers', async function () {
let drag = driver.findElement(webdriver.By.xpath('//*[#id="LiveScheduleList"]/ul/li[1]/div[2]'));
let drop = driver.findElement(webdriver.By.xpath('//*[#id="LiveScheduleList"]/ul/li[2]/div[2]'));
await driver.sleep(2500);
await driver.executeScript("document.querySelector('#ChangeOrderBtn').click();");
await driver.sleep(2500);
await actions.dragAndDrop(drag, drop);
});
};
When I run it I get this back:
TypeError: actions.dragAndDrop is not a function
You are using actions incorrectly.
Your code should look like...
await driver.
actions().
dragAndDrop(drag, drop);
PD: BTW, using sleep to synchronize your code is not a best practice...
"use strict";
require("./helpers/setup");
var wd = require("wd"),
_ = require('underscore'),
serverConfigs = require('./helpers/appium-servers'),
Q = require('q');
describe("Windows test from Node", function () {
this.timeout(300000);
var driver;
var allPassed = true;
before(function () {
var serverConfig = serverConfigs.local;
driver = wd.promiseChainRemote(serverConfig);
require("./helpers/logging").configure(driver);
var desired = _.clone(require("./helpers/caps").CMS);
return driver
.init(desired);
});
after(function () {
return driver
.quit();
});
afterEach(function () {
allPassed = allPassed && this.currentTest.state === 'passed';
});
it("should open CMS.", function () {
return driver
.elementByName('CharwellDB').doubleclick()
.sleep(20000);
});
it("should login CMS.", function () {
return driver
.elementByAccessibilityId('m_tbUserID').sendKeys("")
.elementByAccessibilityId('m_tbPassword').sendKeys("")
.elementByAccessibilityId('m_btnOk').click();
});
});
Hi, I'm using https://github.com/Clemensreijnen/AppiumOnWindowsWithJS/blob/master/README.md
framework and trying to automate a desktop application. After "should open CMS", a new desktop window open and the winappdriver couldn't locate the element on that window, I tried to work with WindowHandle but not going well with JavaScript, Please give some advise, thanks in advance!
I couldn't find my source code, but the solution is to implement windowHandle and as well as promise in JavaScript.
I am trying to read the Chrome console using Selenium Webdriver in node.js, but so far it is unsuccessful. There are no errors. But all it returns is an empty array [].
The following is a snippet of the HTML and JavaScript function. When run manually in Chrome, these write to the console just fine.
<button name="button1" type="button" onclick="test_console()">Test</button>
function test_console() {
console.log("Hello World");
}
The following is the code I am using in node.js to try to get the output to Chrome.
const webdriver = require('selenium-webdriver');
const chromeDriver = require('selenium-webdriver/chrome');
const logging = require('selenium-webdriver').logging;
const path = require('chromeDriver').path;
const service = new chromeDriver.ServiceBuilder(path).build();
chromeDriver.setDefaultService(service);
const {By, Key} = webdriver;
webdriver.promise.USE_PROMISE_MANAGER = false;
const CHROME_BIN_PATH = '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome';
const prefs = new logging.Preferences();
prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL);
const options = new chromeDriver.Options();
options.setChromeBinaryPath(CHROME_BIN_PATH);
options.addArguments(
'headless',
'disable-gpu',
'verbose',
'disable-impl-side-painting',
);
const main = async () => {
try {
const driver = await new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.setLoggingPrefs(prefs)
.forBrowser('chrome')
.setChromeOptions(options)
.build();
await driver.get('http://example.com/example.html');
//clicking this button manually in Chrome writes to the console
await driver.findElement(By.name('button1')).click();
await driver.manage().logs().get(logging.Type.BROWSER)
.then(function(entries) {
console.log(entries);
});
await driver.close();
await driver.quit();
} catch (error) {
await driver.close();
await driver.quit();
console.log(error);
}
};
main();
I'm sure the issue is simple, probably a configuration problem. I just cant figure out what the problem might be. I even resorted to reading the webdriver source code in Git to see if I could see anything, but to no avail.
As far as I can tell, getting the contents of the console from Chrome using webdriver is a no go.
I ended up solving the issue in this manner:
//append a div to the body of the page
await driver.executeScript("var div = document.createElement('div'); div.id = 'console_log'; document.body.appendChild(div);");
//override console.log to write the log message to the new div
await driver.executeScript("console.log = function(message){document.getElementById('console_log').innerHTML += message}");
//get the contents of the new div
const console_log = await driver.findElement(By.id('console_log'));
console.log(await console_log.getAttribute('innerHTML'));
Good day.
In JS/node I'm new.
I'm does made two functions from main code into a separate file and now I can not connect it to the main.
If I fighting over this issue. Help me plz. Something I'm doing wrong.
Here are the features that made:
exports.loadRegistrationForm = function() {
driver.get('http://somesite');
driver.getTitle().then(function(title){
if("sometitle"===title){
driver.findElement(webdriver.By.xpath('html/body/div/header/div/div/div[2]/div[2]/a[1]'))
.click();
};
});
driver.wait(function(){
return driver.isElementPresent(webdriver.By.name('fos_user_registration_form[email]'));
}, 3000, 'Failed to load Registration form');
}
exports.fillingRegistrationForm = function(inputEmail, inputPassword, errElement, errMessage){
driver.findElement(webdriver.By.name('fos_user_registration_form[email]'))
.sendKeys(inputEmail);
driver.findElement(webdriver.By.name('fos_user_registration_form[plainPassword]'))
.sendKeys(inputPassword);
driver.findElement(webdriver.By.id('btn-submit')).click();//сабмит
driver.wait(function(){
return driver.isElementPresent(webdriver.By.xpath(errElement));
}, 3000, 'Элемент не найден');
var flow = webdriver.promise.controlFlow();
function getErrObject(){
errObject = driver.findElement(webdriver.By.xpath(errElement))
.getText()
}
flow.execute(getErrObject).then(function(){
if(errObject.value_ === errMessage){
assert.equal(errObject.value_, errMessage);
console.log('OK')
};
});
}
Here are trying to rewrite part of the core functions:
var assert = require("assert")
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
var loadRegistrationForm = require('reusable_function').loadRegistrationForm;
var fillingRegistrationForm = require('./reusable_function').fillingRegistrationForm
describe('Check the Email field of the registration form.', function(){
it('Enter an already registered Email', function(done){
var inputEmail = '123#ya.ru';
var inputPassword = '12345678Aa';
var errElement = "//*[#class='form-errors server-error']";
var errMessage = 'Email already in use';
loadRegistrationForm();
fillingRegistrationForm(inputEmail, inputPassword, errElement, errMessage);
return done();
});
});
In the console error:
ReferenceError: driver is not defined
at exports.loadRegistrationForm (C:\Program Files\nodejs\test\reusable_fun
ction.js:9:5)
at Context.<anonymous> (C:\Program Files\nodejs\test\test2_mocha.js:15:9)
at callFnAsync (C:\Users\Valentine11\AppData\Roaming\npm\node_modules\moch
a\lib\runnable.js:306:8)
at Test.Runnable.run (C:\Users\Valentine11\AppData\Roaming\npm\node_module
s\mocha\lib\runnable.js:261:7)
at Runner.runTest (C:\Users\Valentine11\AppData\Roaming\npm\node_modules\m
ocha\lib\runner.js:421:10)
at C:\Users\Valentine11\AppData\Roaming\npm\node_modules\mocha\lib\runner.
js:528:12
at next (C:\Users\Valentine11\AppData\Roaming\npm\node_modules\mocha\lib\r
unner.js:341:14)
at C:\Users\Valentine11\AppData\Roaming\npm\node_modules\mocha\lib\runner.
js:351:7
at next (C:\Users\Valentine11\AppData\Roaming\npm\node_modules\mocha\lib\r
unner.js:283:14)
at Immediate._onImmediate (C:\Users\Valentine11\AppData\Roaming\npm\node_m
odules\mocha\lib\runner.js:319:5)
What am I doing wrong? Incorrectly write access functions from loadable module? How does it right?
Great thanks.
Upd. Okay I find answer.
Every module in JS have own scope. In module reusable_function no driver variable, hence the error not defined. Driver is a variable in the main module, but it is invisible to the module reusable_function, because it is not included in the scope. So I have defined a variable driver in the module reusable_function and removed this variable from the main module. To delete a variable from the main driver module does not disturb his work, because the variable driver cache and made available during the import module reusable_function.
Reusable_function:
var assert = require("assert")
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build()
exports.loadRegistrationForm = function(){
driver.get('http:...');
driver.getTitle().then(function(title){
if("..."===title){
driver.findElement(webdriver.By.xpath('html/body/div/header/div/div/div[2]/div[2]/a[1]'))
.click();
};
});
driver.wait(function(){
return driver.isElementPresent(webdriver.By.name('fos_user_registration_form[email]'));
}, 3000, 'Failed to load Registration form');
};
exports.fillingRegistrationForm = function(inputEmail, inputPassword, errElement, errMessage){
driver.findElement(webdriver.By.name('fos_user_registration_form[email]'))
.sendKeys(inputEmail);
driver.findElement(webdriver.By.name('fos_user_registration_form[plainPassword]'))
.sendKeys(inputPassword);
driver.findElement(webdriver.By.id('btn-submit')).click();//сабмит
driver.wait(function(){
return driver.isElementPresent(webdriver.By.xpath(errElement));
}, 3000, 'Element not found');
var flow = webdriver.promise.controlFlow();
function getErrObject(){
errObject = driver.findElement(webdriver.By.xpath(errElement))
.getText()
}
flow.execute(getErrObject).then(function(){
if(errObject.value_ === errMessage){
assert.equal(errObject.value_, errMessage);
console.log('OK')
};
});
};
Main module (part of):
var webdriver = require('selenium-webdriver');
var flow = webdriver.promise.controlFlow();
var loadRegistrationForm = require('./reusable_function').loadRegistrationForm
var fillingRegistrationForm = require('./reusable_function').fillingRegistrationForm
describe('Check out Email form field.', function(){
it('Enter already register Email', function(done){
var inputEmail = '123#ya.ru';
var inputPassword = '12345678Aa';
var errElement = "//*[#class='form-errors server-error']";
var errMessage = 'Email already in use';
loadRegistrationForm();
fillingRegistrationForm(inputEmail, inputPassword, errElement, errMessage);
flow.execute(function(){
return done();
});
});
});
Its work.
You have a random funtion execute right above the error line which ends without any code. Remove this and it will work.