Javascript Mocha Selenium Test not working - javascript

I am trying to run a selenium mocha test to check the title of the website google. I am doing this in the configuration of Web.js and WebTest.js. Here are my classes and I'm not sure if I'm going at this the correct way or not.
Web.js
const {Builder, By, Key, until, WebElement} = require('selenium-webdriver');
var driver = new Builder().forBrowser('internet explorer').build();
var url = 'https://www.google.com/';
function Web() {
var promise = new Promise(function(resolve,reject){
return driver.get(url);
}).then(function(title) {
var title;
title = driver.getTitle().toString();
return title;
}).catch(function(err){
console.log(err);
});
return title;
}
Web.prototype.getTitle = function (title) {
var title = Web();
while (title == null){
title = Web();
}
return (title);
}
module.exports.Web = Web;
WebTest.js
assert = require("assert");
Web = require("../Web.js").Web
describe("A web function", function () {
describe("getting google's title", function () {
it("should return Google", function () {
var result = new Web().getTitle();
assert.equal("Google", result, "But the string " + result + " was returned instead");
});
});
});
I am getting the error "ReferenceError: title is not defined" which leads me to believe I have a scope problem, but I'm not sure how to do this correctly.
Thank you for any help.

This should work:
var webdriver = require("selenium-webdriver");
var DriverFactory = {
create: function (browser) {
return driver = new webdriver
.Builder().forBrowser(browser)
.build();
}
}
module.exports = DriverFactory;
And then use this module in your test
var DriverFactory = require('./driverFactory.js');
var assert = require("chai").assert;
describe("Get title", function () {
this.timeout(40000);
var driver;
before(async function () {
driver = await DriverFactory.create("firefox");
});
after(async function () {
await driver.quit();
});
it("1.Open Google website", async function () {
await driver.get("https://www.google.com");
});
it("2.The title is 'Google'", async function () {
var title = await driver.getTitle();
assert.equal(title, "Google");
});

Related

How do I consume and print a Promise result?

I'm trying to get the current block number from Binance Smart Chain (BSC).
In the documentation, provider.getBlockNumber() returns a Promise object.
Here are my attempts to consume and print the current block number into console.
I'm using Node.js v16.5.0 and Ethers.js 5.4.1.
var ethers = require("ethers");
var url = "wss://bsc-ws-node.nariox.org:443";
const provider = new ethers.providers.WebSocketProvider(url);
const blockNumber = async function() {
return await provider.getBlockNumber();
}
console.log(blockNumber());
process.exit();
This returns Promise { <pending> } on the console.
This block of code:
var ethers = require("ethers");
var url = "wss://bsc-ws-node.nariox.org:443";
const provider = new ethers.providers.WebSocketProvider(url);
async function blockNumber() {
const blockNumber = await provider.getBlockNumber();
return blockNumber();
}
blockNumber().then(data => {console.log(data)});
process.exit();
output exactly nothing in the console, almost as there's nothing wrong in the code.
Expected output should be a number, like 9380976.
Where did I go wrong?
EDIT 1: Added process.exit() because that's supposed to be in the original post.
ANSWER by #purple:
var ethers = require("ethers");
var url = "wss://bsc-ws-node.nariox.org:443";
const provider = new ethers.providers.WebSocketProvider(url);
async function blockNumber() {
const blockNumber = await provider.getBlockNumber();
return blockNumber;
}
blockNumber().then(data => {
console.log(data)
process.exit();
});
Result:
> node app
*pauses for a bit, then prints*
9397167
>
Did you mean return blockNumber; instead of return blockNumber();?

WinAppDriver canonot find element when new window of desktop application created

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

object is not a constructor Protractor Java Script

I keep getting this message saying Newpage is not a constructor i have racked my brains out for the past 5 hours trying to resolve this issue and no progress i have looked at the following sites
How to call a function in another function in protractor
'TypeError: undefined is not a function' using Protractor
Maybe it is something simple i don't know. All I am trying to do is call a function form my page object file. Still no success any help would be appreciated.
my code:
var newPage = require('./newPage.js');
describe('Get Payroll Information', function() {
beforeAll(function(){
var newPageObj = new newPage();
});
var EC = protractor.ExpectedConditions;
var status;
var clientid, weeknum, pdate;
it('Get CycleStatus, Paydate, Weeknumber, Clientid - completed', function () {
const fs = require('fs');
const cycle = $('#cycleStatusID'); // cycle status
const client = $('#clientID'); // clientid
const week = $('#companyIdBar_weekId'); // week number
const payDate = $('#companyIdBar_processDateId');
//------------Get PayDate --------------------------------
.then(() => {
payDate.isPresent().then(function(present){
if(present){
payDate.getText().then(function(text){
pDate = text;
console.log('paydate (' + pDate + ') is displayed');
});
} else {
console.log('pay date not present');
//return;// breaks for loop like (break)
}
})
})
.then(() => {
writeValueToFile(cycleStatus,clientID,weekNum,pDate);
})
.then(() => {
newPageObj.goBack();
console.log('return to support');
});
});// master then promise
});//spec function
Protractor console message
newPage.js Code:
newPage = function(){
function goBack(){
var returnbtn = $('#returnToADPClick');
var search1 = ($$('input[id="toolbarQuickSearch"]').get(0));
returnbtn.click();
browser.wait(EC.elementToBeClickable(search1),20,000);
};
};
module.exports = new newPage();
changed to module.exports = new newPage; // this work now i get
Your newPage.js is exporting an object, not a function/class/constructor. Change the module.exports to just newPage like this:
newPage = function(){
function goBack(){
var returnbtn = $('#returnToADPClick');
var search1 = ($$('input[id="toolbarQuickSearch"]').get(0));
returnbtn.click();
browser.wait(EC.elementToBeClickable(search1),20,000);
};
};
module.exports = newPage;
Failed: newPageObj Object not defined
This is because of the scope of the newPageObj variable - currently it is only defined in the scope of beforeAll. Declare your variable at the higher level:
var newPage = require('./newPage.js');
var newPageObj;
describe('Get Payroll Information', function() {
beforeAll(function() {
newPageObj = new newPage();
});
// ...
});

'ReferenceError: driver is not defined' when I try to call a function from a loadable file

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.

Error logging to file not working in javascript windows store app

I am trying to write console log to a file. I tried this way and a log file is created but no contents are appended to it.Calling it at the start of the app. Am i doing something wrong.
function startFileLog() {
// choose where the file will be stored:
var fileDestination = Windows.Storage.ApplicationData.current.localFolder;
var logger = new WinJS.Promise(function (complete) {
var logfilename = new Date().toISOString().replace(/[:-]/g, "");
logfilename = "log-" + logfilename + ".log";
fileDestination.createFileAsync(logfilename,
Windows.Storage.CreationCollisionOption.generateUniqueName)
.done(function (file) {
complete(file);
});
});
var actionFn = function (message, tag, type) {
logger.then(function (file) {
var m = WinJS.Utilities.formatLog(message, tag, type);
Windows.Storage.FileIO.appendTextAsync(file, m).done();
});
};
WinJS.Utilities.startLog({ action: actionFn });
}

Categories