Trying to run headless chrome in nodejs using mocha but it gives me an error - selenium-webdriver

Below is the code to run test headless in nodejs using mocha. But I keep getting "SyntaxError: Unexpected end of input" can someone help ?
var assert = require('assert');
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
var test = require('selenium-webdriver/testing');
var driver;
const timeOut = 15000;
const chromeCapabilities = webdriver.Capabilities.chrome();
chromeCapabilities.set('chromeOptions', {args: ['--headless', '--disable-gpu','--no-sandbox','--disable-dev-shm-usage']});
var site_root_url = "file://" + __dirname + "/../../site"
String.prototype.contains = function(it) { return this.indexOf(it) != -1; };
test.describe('Browser Headless', function() {
test.before(function() {
});
test.after(function() {
});
test.beforeEach(function() {
// this.timeout(timeOut);
});
// test cases
var url = "";
test.it("Headless with Chrome", function() {
this.timeout(timeOut);
driver = new webdriver.Builder()
.forBrowser('chrome')
.withCapabilities(chromeCapabilities)
.build();
driver.get("http://travel.agileway.net")
driver.getTitle().then(function(the_title){
assert.equal("Agile Travel", the_title)
});
driver.quit
});
I tried running it without mocha but it still didn't work. I don't know what I am doing wrong.

Related

PATCH Request fails for one endpoint, but does work for other endpoints

I'm a bit new to testing and am working on editing tests for a MEAN-stack web app generated by the yeoman angular-fullstack generator. I've POSTed a dummy object into my mongo database and can see the object and its ID through the mongo shell.
I can perform GET and PUT requests on the object; however, trying to perform a PATCH request on the ID returns OPERATION_PATH_UNRESOLVABLE.
Does anyone have any suggestions as to why this may be happening?
I've included a sample of the code below, this code works perfectly for my other endpoints. I'm only receiving the error with one specific endpoint.
describe('PATCH /api/objects/:id', function() {
var patchedObject;
beforeEach(function(done) {
newObject.title = 'Patched Object';
newObject.section.Title = 'Patched Object Sec Title';
newObject.section.Body = 'Patched Object Sec Body';
newObject.section.Lists = ['Patched Sec List Item 0'];
newObject.images = ['N/A'];
newObject.date.startDate = '1/5/19';
newObject.date.endDate = '1/10/19';
newObject.duration = '5 Days';
newObject.location = 'VA';
newObject.isProgram = true;
newObject.hasRegistration = true;
newObject.linksOut.title = 'Patched Link';
newObject.linksOut.address = 'Patched Address';
newObject.backGround = 'black';
newObject.orderIndex = objects.length;
request(app)
.patch(`/api/promotions/${newObject._id}`)
.set('authorization', 'Bearer ' + token)
.send(newObject)
.expect(200)
.expect('Content-Type', /json/)
.end(function(err, res) {
if(err) {
return done(err);
}
patchedObject = res.body;
done();
});
});
afterEach(function() {
patchedObject = {};
});
it('should respond with the patched promotion when authenticated',
function() {
expect(patchedObject.title).to.equal('Patched Object');
});
});
I expect the output to be 200 but receive 500 Internal Server Error.
My Logger returns OPERATION_PATH_UNRESOLVABLE

How to write an testcase for $interval in karma along with promises?

I am very new to Karma test cases and it seems to be a tricky and challenging task to write an test case for my mock up result:
My Service function looks like this and its working fine:
var api = new Api(xyz);
// maxTimer is 5 minutes
var maxTimer = 1000 * 60 * 5;
var dataSearchTimeout = maxTimer;
var delayCall = 2000;
var data, dataSearch;
function getResults(id, prevDeferred) {
var deferred = prevDeferred || $q.defer();
function stopGettingSizingResults() {
$interval.cancel(dataSearch);
dataSearch = undefined;
dataSearchTimeout = maxTimer;
}
function handleSuccessResponse(data) {
if (data.status === CONSTANT.STATUS.READY) {
stopGettingResults();
deferred.resolve(data);
} else {
if (!dataSearch) {
dataSearch = $interval(function () {
getResults(id, deferred);
}, delayCall);
}
dataSearchTimeout = dataSearchTimeout - delayCall;
if (dataSearchTimeout <= 0) {
stopGettingResults();
handleErrorResponse();
}
}
}
function handleErrorResponse(response) {
deferred.reject(response);
}
api.get({'id': id}).then(handleSuccessResponse, handleErrorResponse);
return deferred.promise;
}
I am playing for no results by updating the mockup data to 'Not Ready' and that is checking up with this condition data.status === CONSTANT.STATUS.READY and keeps on checking for 5 minutes as declared here: var maxTimer = 1000 * 60 * 5; and successfully throws error.
I am facing challenge to simulate the same from Karma test case:
I tried writing this and I am stuck and not able to proceed further:
it('should throw error timeout happens', inject(function(CONSTANT, $httpBackend, $q) {
var results = {status: 'Not Ready'};
CONSTANT.maxTimer = 100 * 60 * 5;
$httpBackend.expectGET(apicall).respond(results);
}));
It would be a great help if this can be continued, so that I can learn as well.

Selenium Java Script Webdriver using Mocha - take screenshot if test fails

Using Selenium webdriver (Java Script) and Mocha
var assert = require('assert'),
test = require('selenium-webdriver/testing'),
until = require('selenium-webdriver').until,
webdriver = require('selenium-webdriver');
If test fails, I want to take a screen shot using after function from Mocha:
function writeScreenshot(data, name) {
name = name || 'ss.png';
var screenshotPath = '/result/';
fs.writeFileSync(screenshotPath + name, data, 'base64');
};
afterEach(function () {
if (this.currentTest.state == 'failed') {
console.log("If condition");
driver.takeScreenshot().then(function (data) {
writeScreenshot(data, 'failed.png');
});
}
});
After running the test, if condition returned true. But it does not create a screenshot.
See https://github.com/webdriverio/webdriverio/issues/269#issuecomment-306342170 - use afterTest and browser.saveScreenshot if !test.passed in wdio.conf.js

Change country cookie in selenium webdriver using mocha

I want to check certain elements on a website with different country cookie.
I tried using addCookie() but it is not working for me. Below is the code.Please let me know where am I going wrong.
var assert = require('assert'),
test = require('selenium-webdriver/testing'),
webdriver = require('selenium-webdriver');
var url = process.env.URL;
var driver;
function createDriver() {
var driver = new webdriver.Builder()
.usingServer('http://localhost:4444/wd/hub')
.withCapabilities(webdriver.Capabilities.firefox())
.build();
driver.manage().timeouts().setScriptTimeout(15000);
return driver;
}
test.describe('Checking Ringo Home Page', function() {
this.timeout(20000);
test.before(function(){
driver = createDriver();
});
test.after(function(){
driver.quit();
});
test.it('Wifi Element', function() {
driver.get(url).then(function(){
driver.manage().addCookie("src_country", "GB", "http://www.ringo.co");
driver.navigate().refresh().then(function(){
driver.sleep(1000);
driver.manage().window().maximize().then(function(){
driver.findElement(webdriver.By.xpath(".//*[#id='features-option']/div[2]/div[1]/div/span")).then(function(element){
console.log("Wifi Present")
element.isDisplayed().then(function(value){
if(value){
console.log("Wifi Visible");
}else{
assert.fail("Wifi Missing");
}});});});});});})
})
This worked for me
var assert = require('assert'),
test = require('selenium-webdriver/testing'),
webdriver = require('selenium-webdriver');
var url = process.env.URL;
var driver;
function createDriver() {
var driver = new webdriver.Builder()
.usingServer('http://localhost:4444/wd/hub')
.withCapabilities(webdriver.Capabilities.firefox())
.build();
driver.manage().timeouts().setScriptTimeout(15000);
return driver;
}
test.describe('Checking Ringo Home Page', function() {
this.timeout(50000);
test.before(function() {
driver = createDriver();
});
test.after(function() {
driver.quit();
});
test.it('Wifi Element', function() {
driver.get(url).then(function() {
driver.sleep(1000);
driver.manage().addCookie("src_country", "GB");
driver.manage().getCookie('src_country').then(function(cookie) {
console.log(cookie.value);
});
driver.navigate().refresh().then(function() {
driver.sleep(1000);
driver.manage().window().maximize().then(function() {
driver.findElement(webdriver.By.xpath(".//*[#id='features- option']/div[2]/div[1]/div/span")).then(function(element) {
console.log("Wifi Present")
driver.executeScript("scroll(0,700)");
driver.sleep(500)
element.isDisplayed().then(function(value) {
if (value) {
console.log("Wifi Visible");
} else {
assert.fail("Wifi Missing");
}
});
});
});
});
});
});
})
Cheers :)

authwithcustomtoken not working

In my project I am writing e2e tests in node.js and I have a test firebase I am using. So I create a token in node before each describe in the test runs and then I send it to the front end(angular.js) and then I use the authWithCustomToken function to authenticate the person.
The problem is for some reason it isn't even calling the function because I put a console.log statement in the callback and every time my code runs it enters the if $location.search condition but the console.log doesn't print out anything. I dont seem to know what the problem is.
var Firebase = require('firebase');
var FirebaseTokenGenerator = require('firebase-token-generator');
var rootRef = new Firebase('https://xxxxx');
var data = require('./data_helper.js');
rootRef.child('users').set(data.users[0]);
var credentials = {
nonAdmin: {
uid: 'google',
email: 'xxxx'
},
admin: {
uid: 'google',
email: 'xxxxx'
}
};
var logInAndThen = function(options) {
var secret = 'sdmdfmdsjwdsjwjwwewewe';
var tokenGenerator = new FirebaseTokenGenerator(secret);
var token = tokenGenerator.createToken(credentials[options.userType || 'admin']);
browser.get('/login?token=' + token);
var alertDiv = by.className('alert');
//browser.wait(function(){});
var waitOnFirebase = browser.wait(function() {
return browser.isElementPresent(alertDiv);
});
waitOnFirebase.then(function(data) {
console.log('-------', data);
options.cb(data);
});
};
module.exports = logInAndThen;
--------- FRONT END ANGULAR CODE PUT IN APPLICATION.RUN---------------------
if($location.search().token) {
console.log(Refs.root.toString());
Refs.root.authWithCustomToken($location.search().token, function(err, authData) {
console.log(err,authData);
}, {scope: 'email'});
}
I would appreciate it if someone could help me with this
Try getting the token like this (put this in your .run):
var loc = $location.path();
if(loc.search('login?token') > 0) {
token = loc.splice(13)
//now incorporate the 'token' into whatever auth functions you need to.
}
Not entirely sure if this is the most technically 'correct' way of grabbing the token, but it should work for you.

Resources