I want to set the test spec name as the test name in browserstack. Below is my browserstack stack config file. I am using protractor.
exports.makeDefaultCapabilities = function(that) {
return {
browserName: 'chrome',
chromeOptions: {
prefs: {
credentials_enable_service: false,
args: [
'disable-infobars=true',
]
},
loggingPrefs: {
driver: 'WARNING',
server: 'WARNING',
browser: 'INFO'
},
'browserstack.user': 'xx'
'browserstack.key': 'xxx',
'browserstack.debug': true,
};
};
exports.config = {
suites: {
smoke: [
'*/*.js'
]
},
SELENIUM_PROMISE_MANAGER: false,
baseUrl: undefined,
framework: 'jasmine',
allScriptsTimeout: 100000,
getPageTimeout: 100000,
maxSessions: 1,
seleniumAddress: 'https://hub-cloud.browserstack.com/wd/hub',
getMultiCapabilities: function() {
let that = this;
return new Promise(function(resolve) {
let defaults = exports.makeDefaultCapabilities(that);
let capabilities = [];
capabilities.push({
os: 'OS X',
os_version: 'High Sierra'
});
_.forEach(capabilities, function(capability) {
_.defaultsDeep(capability, defaults);
});
resolve(capabilities);
});
},
beforeSession: function(config, capabilities, specs) {
capabilities.name = specs && specs[0].split('/').pop() || undefined;
},
onPrepare: function() {
jasmine.getEnv().addReporter(failFast.init());
let reporter = new SpecReporter();
jasmine.getEnv().addReporter(reporter);
}
};
The beforeSession hook doesn't update the test name in browserstack as the test spec name.
Looking forward for any suggestion. Appreciate your help.
Thanks
Include const request = require('request'); in the *.conf.js file and following snippet in onPrepare() function. This will get the name of your test spec and change the name using BrowserStack REST API.
jasmine.getEnv().addReporter({
specStarted: function(result) {
browser.getCapabilities().then(function (capabilities) {
browser.getSession().then(function(session){
var sessionID = session.getId()
var headers = {
'Content-Type': 'application/json'
};
var dataString = `{"name":"${result.fullName}"}`;
var options = {
url: 'https://api.browserstack.com/automate/sessions/' + sessionID + '.json',
method: 'PUT',
headers: headers,
body: dataString,
auth: {
'user': browserstackUser,
'pass': browserstackKey
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
});
});
}
});
Related
I've an issue with the Forge viewer I'm developping : Im' trying to host it using Github-page, but it doesn't seem to work correctly.
The issue is on the File tree : when I load the viewer page from the Github pages, the file tree seems stuck on "Loading...". However, it correctly loads when I load the page from localhost.
The code of the File tree :
$(document).ready(function () {
prepareAppBucketTree();
$('#refreshBuckets').click(function () {
$('#appBuckets').jstree(true).refresh();
});
$('#createNewBucket').click(function () {
createNewBucket();
});
$('#createBucketModal').on('shown.bs.modal', function () {
$("#newBucketKey").focus();
})
$('#hiddenUploadField').change(function () {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
var _this = this;
if (_this.files.length == 0) return;
var file = _this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
_this.value = '';
}
});
break;
}
});
});
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
console.log(bucketKey)
jQuery.post({
url: '/api/forge/oss/buckets',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
$('#createBucketModal').modal('toggle');
},
error: function (err) {
if (err.status == 409)
alert('Bucket already exists - 409: Duplicated')
console.log(err);
}
});
}
function prepareAppBucketTree() {
$('#appBuckets').jstree({
'core': {
'themes': { "icons": true },
'data': {
"url": '/api/forge/oss/buckets',
"dataType": "json",
'multiple': false,
"data": function (node) {
return { "id": node.id };
}
}
},
'types': {
'default': {
'icon': 'glyphicon glyphicon-question-sign'
},
'#': {
'icon': 'glyphicon glyphicon-cloud'
},
'bucket': {
'icon': 'glyphicon glyphicon-folder-open'
},
'object': {
'icon': 'glyphicon glyphicon-file'
}
},
"plugins": ["types", "state", "sort", "contextmenu"],
contextmenu: { items: autodeskCustomMenu }
}).on('loaded.jstree', function () {
$('#appBuckets').jstree('open_all');
}).bind("activate_node.jstree", function (evt, data) {
if (data != null && data.node != null && data.node.type == 'object') {
// $("#MyViewerDiv").empty();
var urn = data.node.id;
getForgeToken(function (access_token) {
jQuery.ajax({
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn + '/manifest',
headers: { 'Authorization': 'Bearer ' + access_token },
success: function (res) {
if (res.status === 'success') callByUrn('urn:'+urn);
else $("#MyViewerDiv").html('The translation job still running: ' + res.progress + '. Please try again in a moment.');
},
error: function (err) {
var msgButton = 'This file is not translated yet! ' +
'<button class="btn btn-xs btn-info" onclick="translateObject()"><span class="glyphicon glyphicon-eye-open"></span> ' +
'Start translation</button>'
$("#MyViewerDiv").html(msgButton);
}
});
})
}
});
}
function autodeskCustomMenu(autodeskNode) {
var items;
switch (autodeskNode.type) {
case "bucket":
items = {
uploadFile: {
label: "Upload file",
action: function () {
uploadFile();
},
icon: 'glyphicon glyphicon-cloud-upload'
}
};
break;
case "object":
items = {
translateFile: {
label: "Translate",
action: function () {
var treeNode = $('#appBuckets').jstree(true).get_selected(true)[0];
translateObject(treeNode);
},
icon: 'glyphicon glyphicon-eye-open'
}
};
break;
}
return items;
}
function uploadFile() {
$('#hiddenUploadField').click();
}
function translateObject(node) {
$("#MyViewerDiv").empty();
if (node == null) node = $('#appBuckets').jstree(true).get_selected(true)[0];
var bucketKey = node.parents[0];
var objectKey = node.id;
jQuery.post({
url: '/api/forge/modelderivative/jobs',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'objectName': objectKey }),
success: function (res) {
$("#MyViewerDiv").html('Translation started! Please try again in a moment.');
},
});
}
Please note that Github Pages are used for serving static pages without any special server-side logic. Your Forge application requires a server to talk to as well, for example, to obtain a list of buckets for the tree view (by making a request to /api/forge/oss/buckets).
You could potentially host your application's server-side logic on something like Heroku, and then have your static HTML/CSS/JavaScript page on Github talk to that server (for example, https://my-forge-app.herokuapp.com/api/forge/oss/buckets). Just be careful about CORS.
Oflate , I have been observing below error when ran my protractor tests on browserstack.
"UnhandledPromiseRejectionWarning: WebDriverError: Could not start Browser / Emulator"
Here is my protractor config file.
let browserstack = _.defaults({
user: process.env.BROWSERSTACK_USERNAME,
key: process.env.BROWSERSTACK_ACCESS_KEY
}, {
user: '**',
key: '**'
});
let timeoutMultiplier = 2;
exports.makeDefaultCapabilities = function(that) {
return {
browserName: 'chrome',
chromeOptions: {
prefs: {
credentials_enable_service: false,
},
loggingPrefs: {
driver: 'WARNING',
server: 'WARNING',
browser: 'INFO'
},
'browserstack.user': browserstack.user,
'browserstack.key': browserstack.key,
'browserstack.debug': true,
build: that.params.BUILD_NUMBER || '(unknown)',
maxInstances: 2,
name: that.baseUrl,
}
};
exports.config = {
suites: {
e2e: [
'*/*.spec.js'
]
},
SELENIUM_PROMISE_MANAGER: false,
baseUrl: undefined,
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 60 * 1000 * timeoutMultiplier,
realtimeFailure: true
},
maxSessions: 1,
params: {
BUILD_NUMBER: undefined,
CI: undefined,
TIMEOUT_MULTIPLIER: timeoutMultiplier
},
seleniumAddress: 'https://hub-cloud.browserstack.com/wd/hub',
useAllAngular2AppRoots: true,
getMultiCapabilities: function() {
return new Promise(function(resolve) {
let capabilities = [];
capabilities.push({
os: 'OS X',
os_version: 'High Sierra'
});
resolve(capabilities);
});
},
onPrepare: function() {
browser.manage().window().maximize();
jasmine.getEnv().addReporter(failFast.init());
let reporter = new SpecReporter();
jasmine.getEnv().addReporter(reporter);
}
};
Test that is failing :
calling function :
async clickButton() {
await browser.waitForAngularEnabled(false);
await waitForEl(this.Button);
await browser.sleep(10000);
await this.Button.click();
await browser.sleep(10000);
await this.stopButton.click();
await waitForElAbsence(this.Bar);
await browser.waitForAngularEnabled(true);
}
used above calling function in below spec:
it('should check if button is clicable', async function() {
let po = new check({
url
});
await po.go();
await po.clickButton();
});
Has any one experienced it before ? Also the error is seen only browserstack and not on my local computer. Also the test i pasted is not the only one failing . Tests are failing randomly with this error.
I have protractor v5.3.2
when i run gulp to start protractor i got this error
E/launcher - unknown error: cannot parse capability: proxy
from unknown error: proxyType is 'manual' but no manual proxy capabilities were found
(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299
x86_64)
protractor version 5.1.1
gulpfile
ar gulp = require('gulp');
var path = require('path');
var child_process = require('child_process');
var requireDir = require('require-dir');
requireDir('./config/gulp/tasks');
var runSequence = require('run-sequence');
var open = require('gulp-open');
gulp.task('default', [
//'complete'
'protractor-test'
]);
function getBinary(packageName, binaryLocation) {
var pkgPath = require.resolve(packageName);
return path.resolve(path.join(path.dirname(pkgPath), '..', binaryLocation));
}
gulp.task('protractor-install', function(done) {
var binary = getBinary('webdriver-manager', '../bin/webdriver-manager');
child_process.spawn('node', [binary, 'update --versions.chrome 2.29'], {
stdio: 'inherit'
}).once('close', function() {
done();
});
});
gulp.task('protractor-start', function(done) {
var binary = getBinary('protractor', 'bin/protractor');
child_process.spawn('node', [binary, 'protractor.conf.js'], {
stdio: 'inherit'
}).once('close', function() {
gulp.src('protractor-results/report.html')
.pipe(open({ app: 'chrome' }));
done();
});
});
gulp.task('t', function() {
runSequence('start-server',
'start-proxy',
'protractor-start',
'stop-servers');
});
gulp.task('debug-proxy', function(done) {
child_process.spawn('C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', ['--proxy-server=http=localhost:8080', '--user-data-dir=C:\\tmp', 'http://localhost:49852'], {
stdio: 'inherit'
}).once('close', function() {
done();
});
});
and the config of protractor
exports.config = {
directConnect: true,
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
prefs: {
'credentials_enable_service': false,
'profile': {
'password_manager_enabled': false
}
}
},
'proxy': {
'proxyType': 'manual',
'httpsProxy': 'localhost:3000'
}
},
framework: 'jasmine',
specs: [
'Tests/Common/common-e2e-spec.js',
// 'Tests/S4B/skype4-business-e2e-spec.js',
// 'Tests/CM/client-management-e2e-spec.js',
// 'Tests/MC/manage-compute-e2e-spec.js'
],
useAllAngular2AppRoots: true,
baseUrl: 'https://localhost:44300',
beforeLaunch: function() {
return new Promise(function(resolve) {
screenshotreporter.beforeLaunch(resolve);
});
},
onPrepare: function() {
jasmine.getEnv().addReporter(screenshotreporter);
jasmine.getEnv().addReporter(xmlreporter1);
jasmine.getEnv().addReporter(xmlreporter2);
},
afterLaunch: function(exitCode) {
return new Promise(function(resolve) {
screenshotreporter.afterLaunch(resolve.bind(this, exitCode));
});
},
jasmineNodeOpts: {
//1 minute timeout
defaultTimeoutInterval: 60000,
showTiming: true,
print: function() {}
}
};
Make sure to run gulp without sudo!!!
I am running protractor against BrowserStack with multiple browser in parallel. Please refer to 'Speed up testing section in 'https://www.browserstack.com/automate/protractor.
It works great, however if I use 4 instances of webdriver to run the same feature files in parallel, it will 1 html cucumber report.
I've googled this: https://github.com/wswebcreation/protractor-multiple-cucumber-html-reporter-plugin, which seems to be able to generate multiple json file, but no html files.
I am new to protractor. Could anyone give some suggestions, or some code change or plugin that can make this happen?
Thank,
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
var JasmineReporters = require('jasmine-reporters');
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
framework: 'jasmine2',
multiCapabilities: [
{
browserName: 'chrome',
shardTestFiles: false,
maxInstances: 1,
specs: [
'./tmp/specs1.spec.js',
'./tmp/specs2.spec.js'
],
chromeOptions: {
args: [
'--window-size=1920,1080'],
prefs: {
download: {
prompt_for_download: false,
default_directory: './downloads',
}
}
}
},
{
browserName: 'chrome',
shardTestFiles: false,
maxInstances: 1,
specs: [
'./tmp/specs3.spec.js',
'./tmp/specs4.spec.js'
],
chromeOptions: {
args: [
'--window-size=1920,1080'],
prefs: {
download: {
prompt_for_download: false,
default_directory: './downloads',
}
}
}
}
],
allScriptsTimeout: 600000,
jasmineNodeOpts: {
defaultTimeoutInterval: 600000,
showColors: true
},
onPrepare: function() {
browser.driver.getCapabilities().then(function(caps) {
browser.browserName = caps.get('browserName');
});
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
browser.getProcessedConfig().then(function(config) {
var capabilities = config.capabilities;
jasmine.getEnv().addReporter(
new Jasmine2HtmlReporter({
savePath: './reports/',
takeScreenshots: true,
screenshotsFolder: './screenshots',
filePrefix: 'protractor-demo-tests-report-' + capabilities.platform + '-' + capabilities.browserName,
consolidateAll: false,
takeScreenshotsOnlyOnFailures: true,
})
);
});
var jasmineReporters = require('jasmine-reporters');
return browser.getProcessedConfig().then(function(config) {
// you could use other properties here if you want, such as platform and version
var browserName = config.capabilities.browserName;
var junitReporter = new jasmineReporters.JUnitXmlReporter({
consolidateAll: false,
savePath: 'reports/jUnitXmlReporter',
modifyReportFileName: function(generatedFileName, suite) {
return browserName + '.' + generatedFileName;
}
});
jasmine.getEnv().addReporter(junitReporter);
//set window size to max available
setTimeout(function() {
browser.driver.executeScript(function() {
return {
width: window.screen.availWidth,
height: window.screen.availHeight
};
}).then(function(result) {
browser.driver.manage().window().setPosition(0,0);
browser.driver.manage().window().setSize(result.width, result.height);
});
});
});
}
};
below provided is the config file and the stepdefinition file. after running it says
2 scenarios (2 passed)
7 steps (7 passed)
0m00.001s
E/launcher - expected 'Hello Ayush!' to equal 'Hello Rahul!'
Process exited with error code 199
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
module.exports = function() {
this.Given(/^I go to "([^"]*)"$/, function(site) {
browser.get(site);
});
this.When(/^I add "([^"]*)" in the task field$/, function(task) {
element(by.model('todoList.todoText')).sendKeys(task);
});
this.When(/^I typed name in the field$/, function() {
element(by.model('yourName')).sendKeys('Ayush');
});
this.Then(/^I click the add button$/, function() {
var el = element(by.css('[value="add"]'));
el.click();
});
this.Then(/^I should see my new task in the list$/, function(callback) {
var todoList = element.all(by.repeater('todo in todoList.todos'));
expect(todoList.count()).to.eventually.equal(3);
expect(todoList.get(2).getText()).to.eventually.equal('Be Awesome');
callback();
});
this.Then(/^The name should be displayed in the greeting$/, function() {
var greeting = element(by.binding('yourName'));
expect(greeting.getText()).to.eventually.equal('Hello Rahul!');
//callback();
});
};
exports.config = {
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
getPageTimeout: 60000,
allScriptsTimeout: 500000,
framework: 'custom',
// path relative to the current config file
frameworkPath: require.resolve('protractor-cucumber-framework'),
capabilities: {
'browserName': 'chrome'
},
// Spec patterns are relative to this directory.
specs: [
'/Users/viveka1/vivek_ayush_angular_ui/feature/login.feature'
],
//baseURL: 'http://localhost:8080/',
baseURL: 'https://angularjs.org/',
cucumberOpts: {
require: '/Users/viveka1/vivek_ayush_angular_ui/step_definition/login.js',
tags: false,
format: 'summary',
profile: false,
'no-source': true
}
};
Try to add callback or return into steps.
like:
this.When(/^I add "([^"]*)" in the task field$/, function(task) {
return element(by.model('todoList.todoText')).sendKeys(task); });