object is not a constructor Protractor Java Script - javascript

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();
});
// ...
});

Related

Loading multiple files with require statement on JS

The execution returns the following error when trying to load multiple js:
TypeError: Cannot read property 'get' of undefined
The solution that I am implementing has a login_steps.js:
var LoginSteps = function() {
var LoginSteps = require("../pages/pages.js");
browser.ignoreSynchronization = true;
this.World = function MyWorld() {
this.page = new LoginSteps();
};
this.Given(/^the page is open$/, function (callback) {
this.page.login_page.get();
callback();
});
};
module.exports = LoginSteps;
A page.js where I want to include all the modules that I need.
var Pages = function() {
module.exports = {
shipments_page: require('./shipments_page.js'),
login_page: require('./login_page.js'),
};
};
module.exports = Pages;
And the modules login_page.js:
var chai = require('chai').use(require('chai-as-promised'));
var expect = chai.expect;
this.get = function() {
browser.get('https://aaa/login');
};
this.setEmail = function(value) {
element(by.id('login-email')).sendKeys(value);
};
this.setPassword = function(value) {
element(by.id('login-password')).sendKeys(value);
};
this.clickAccede = function() {
element(by.id('login-submit')).click()
};
shipment_page.js:
var chai = require('chai').use(require('chai-as-promised'));
var expect = chai.expect;
this.pageIsLoaded = function() {
browser.waitForAngular();
expect(browser.getTitle()).to.be.eventually.equals('title');
};
Then when I execute the test the log shows
Failures:
1) Scenario: User login - features/login.feature:3
Step: Given the page is open - features/login.feature:4
Step Definition: features/steps/login_steps.js:16
Message:
TypeError: Cannot read property 'get' of undefined
at MyWorld.<anonymous> (/Users/mj/IdeaProjects/atpro/features/steps/login_steps.js:17:30)
at process._tickCallback (internal/process/next_tick.js:61:11)
1 scenario (1 failed)
5 steps (1 failed, 4 skipped)
Here is the code that you can try. Its works for me. I modified based on your code snippet. I won't use this pattern in my tests though.You may not want to write protractor-cucumber test using the pattern you are following. One should always use validation/assertions in step definition code. if you do validation in page object, even your validation fails, your test still will show passed.
login_steps.js
var LoginSteps = function() {
var LoginSteps = require("../pages/pages.js");
browser.ignoreSynchronization = true;
this.World = function MyWorld() {
this.page = LoginSteps;
};
this.Given(/^the page is open$/, function (callback) {
this.page.login_page.get();
callback();
});
};
module.exports = LoginSteps;
pages.js:
module.exports = {
shipments_page: require('./shipments_page.js'),
login_page: require('./login_page.js'),
};
If I interpreted correctly this is what you want. You have only to change page.js a little.
module.exports = function() {
this.shipments_page = require('./shipments_page.js');
this.login_page = require('./login_page.js');
};
Please try this. I cannot test at the moment :=)

Javascript Mocha Selenium Test not working

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");
});

DocumentDB connection in js: "require is not defined"

I've been able to create the database and query it. Using Microsoft's tutorial on using node.js to query, I have been able to accomplish this with this code:
// Simple Query
"use strict";
var documentClient = require("documentdb").DocumentClient;
var config = require("./config");
var url = require('url');
// use the previously saved config.endpoint and config.primaryKey to create a new DocumentClient
var client = new documentClient(config.endpoint, { "masterKey": config.primaryKey });
// These urls are how the DocumentDB client will find the right database and collection.
var HttpStatusCodes = { NOTFOUND: 404 };
var databaseUrl = `dbs/${config.database.id}`;
var collectionUrl = `${databaseUrl}/colls/${config.collection.id}`;
// Query JSON document collection
function queryCollection() {
console.log(`Querying collection through index:\n${config.collection.id}`);
return new Promise((resolve, reject) => {
client.queryDocuments(
collectionUrl,
'SELECT VALUE gd.NFL FROM GamblersDenDB gd WHERE gd.id = "SanDiego"'
).toArray((err, results) => {
if (err) reject(err)
else {
for (var queryResult of results) {
let resultString = JSON.stringify(queryResult);
console.log(`\tQuery returned ${resultString}`);
}
console.log();
resolve(results);
}
});
});
};
queryCollection()
Running that js file in my command prompt works! It results in the output:
C:\Users\kenv\Desktop\DocDB Test>node SimpleQuery.js
Querying collection through index:
GamblersDenColl
Query returned {"ID":"SDC","name":"Chargers"}
Great. So now I've transferred my code to my project's folder and try to run in the app with
taco run android --device
When I pull up the console, the first error that sticks out to me is
Uncaught ReferenceError: require is not defined(…)
It's pointing to the line var documentClient = require("documentdb").DocumentClient; in my code.
Here is my complete js file code that's throwing the error:
(function () {
"use strict";
document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );
function onDeviceReady() {
navigator.splashscreen.hide();
console.log("Cordova is READY!");
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
$(".btnURL").on("click", function(){loadURL($(this))});
function loadURL(theObj) {
cordova.InAppBrowser.open(theObj.data("url"), "_blank", "location=yes");
}
//********* jQuery VARIABLES ***************//
var $elBtnSaveName= $("#btnSaveName"),
$elShowClients= $("#btnShowClients"),
$elDivShow= $("#divShow"),
$elFormClient= $("#formClient");
//********** EVENT HANDLERS *****************//
$elShowClients.on("click", queryCollection);
//********************* DOCUMENT DB SECTION *********************************************************/
var documentClient = require("documentdb").DocumentClient;
var config = require("./config");
var url = require('url');
// use the previously saved config.endpoint and config.primaryKey to create a new DocumentClient
var client = new documentClient(config.endpoint, { "masterKey": config.primaryKey });
// These urls are how the DocumentDB client will find the right database and collection.
var HttpStatusCodes = { NOTFOUND: 404 };
var databaseUrl = `dbs/${config.database.id}`;
var collectionUrl = `${databaseUrl}/colls/${config.collection.id}`;
// Query JSON document collection
function queryCollection() {
console.log(`Querying collection through index:\n${config.collection.id}`);
return new Promise((resolve, reject) => {
client.queryDocuments(
collectionUrl,
'SELECT VALUE gd.NFL FROM GamblersDenDB gd WHERE gd.id = "SanDiego"'
).toArray((err, results) => {
if (err) reject(err)
else {
for (var queryResult of results) {
let resultString = JSON.stringify(queryResult);
console.log(`\tQuery returned ${resultString}`);
}
console.log();
resolve(results);
fnShowClientsTable(result.rows);
}
});
});
};
function fnShowClientsTable(data){
var str = "<p><table id='tableResults'";
str += "<tr><th>ID</th><th>Name</th><th class='thEmpty'> </th></tr>" //added class to <th> for formatting
for(var i = 0; i < data.length; i++) { // For X number of times worth of data...
str += "<tr><td>" + data[i].doc.ID +
"</td><td>" + data[i].doc.name +
"</td><td class='btnPencil'>✎</td></tr>";
}
str += "</table></p>"; // END table
$elDivShow.html(str); //Show string as HTML on screen
} // END fnShowClientsTable
//************************* END DOCUMENT DB SECTION ******************************************************/
}; // END onDeviceReady()
function onPause() {
// TODO: This application has been suspended. Save application state here.
};
function onResume() {
// TODO: This application has been reactivated. Restore application state here.
};
} )();
I realize my other function to push it to a string for display in HTML is probably wrong (which I will most certainly have another post about that one :)) but right now I'm trying to determine how I can get past this first error.

'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