We have e2e test with Protractor on headless mode.
We want to test the authentication first.
The behaviour is like the above:
1/ The user tap a link on the browser
2/ the server will check if this user is authenticated or not
2.1 if the user is authenticated, the home page will appear
2.2 if not, the user will be redirect to the sso login page by a
The problem here is that, the javascript won't be executed. I try to add some flags but it doesn't make any difference.
exports.config = {
allScriptsTimeout: 20000,
specs: [
'./e2e/account/**/account.spec.ts',
],
capabilities: {
'browserName': 'firefox',
'marionette': true,
'moz:firefoxOptions': {
args: [ "--headless"],
firefox_binary: '/opt/firefox/firefox',
binary_: '/opt/firefox/firefox',
},
acceptInsecureCerts: true,
javascriptEnabled: true,
},
directConnect: true,
baseUrl: 'http://demop-staging-ppd.com/',
framework: 'mocha',
// SELENIUM_PROMISE_MANAGER: false,
mochaOpts: {
reporter: 'spec',
slow: 3000,
ui: 'bdd',
timeout: 720000
},
beforeLaunch: function() {
require('ts-node').register({
project: 'tsconfig.e2e.json'
});
},
onPrepare: function() {
browser.driver.manage().window().setSize(1280, 1024);
// Disable animations
// #ts-ignore
browser.executeScript('document.body.className += " notransition";');
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
const chaiString = require('chai-string');
chai.use(chaiString);
// #ts-ignore
global.chai = chai;
},
useAllAngular2AppRoots: true
};
the spec file :
before(async () => {
await browser.waitForAngularEnabled(false);
});
it('should content display content ', async () => {
await browser.get('/');
browser.sleep(5000);
const content= await browser.getPageSource();
console.log(content)
});
I'm open to any suggestions and can provide you with any additional information.
[UPDATE]
I change my config file as a above to try enabling javascript on my browse. It works on local but when I try this on docker image dosen't
capabilities: {
'browserName': 'firefox',
'marionette': true,
'moz:firefoxOptions': {
args: ["--headless"],
firefox_binary: '/opt/firefox/firefox',
binary_: '/opt/firefox/firefox',
"prefs": {
"javascript.options.showInConsole": true,
"javascript.enabled": true
},
"log": { "level": "trace" }
},
acceptInsecureCerts: true,
acceptSslCerts: true,
},
multiCapabilities: [ { browserName: 'firefox', firefoxOptions: { args: ['--headless'] }, 'moz:firefoxOptions': { args: [ '--headless' ] } } ]
Please check with this
Use webdriver-manager to execute. With directConnect you will have permission denied error.
I checked in linux PC also. This works fine
Related
FYI, none of the other Stackoverflow questions/answers have resolved this for me.
In an Angular project, we're using Protractor Cucumber Framework for our E2E tests.
I can't figure out how to run only one single test via tags.
You're supposed to be able to edit the tags inside of the cucumberOpts property of the protractor.conf.js file. But when I add a tag #testOnlyThis there, then add that tag to a test in a .feature file, then run npm run e2e:ci (which, according to package.json, runs "protractor ./e2e/protractor.conf.js"), Protractor still runs every single E2E test in our suite. Other changes made in the protractor.conf.js file take effect, but editing the tags seems to have zero effect.
What gives?
protractor.conf.js
// #ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const path = require('path');
const fs = require('fs');
const cucumberJunit = require('protractor-cucumber-junit/lib/cucumber_junit');
const downloadsPath = path.resolve(__dirname, 'downloads');
const reportingPath = path.resolve(__dirname, 'reporting/protractor-cucumber-framework');
let startDate;
/**
* #type { import("protractor").Config }
*/
exports.config = {
allScriptsTimeout: 20000,
specs: ['./src/features/**/**/**/**/**/*.feature'],
resultJsonOutputFile: 'reporting/results.json',
capabilities: {
browserName: 'chrome',
shardTestFiles: true,
maxInstances: 1,
chromeOptions: {
prefs: {
'plugins.always_open_pdf_externally': true,
download: {
directory_upgrade: true,
prompt_for_download: false,
default_directory: downloadsPath,
},
},
args: [
'--no-sandbox',
'--test-type=browser',
'--disable-gpu',
'--log-level=1',
'--disable-dev-shm-usage',
// '--disk-cache-dir=null',
],
},
},
directConnect: true,
SELENIUM_PROMISE_MANAGER: false,
noGlobals: true,
baseUrl: 'https://mybaseurl.com',
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
cucumberOpts: {
require: ['./src/step-definitions/*steps.ts'],
tags: ['#testOnlyThis', '~#ignore'],
format: ['json:./reporting/protractor-cucumber-framework/results.json'],
retry: 2,
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json'),
});
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
},
beforeLaunch() {
startDate = new Date().getTime();
if (!fs.existsSync(downloadsPath)) {
fs.mkdirSync(downloadsPath);
}
if (!fs.existsSync(reportingPath)) {
fs.mkdirSync(reportingPath, { recursive: true });
}
console.log(`process.env.E2E_LANGUAGE is set to: '${process.env.E2E_LANGUAGE}'`);
},
afterLaunch() {
const endDate = new Date().getTime();
const duration = (endDate - startDate) / (60 * 1000);
console.log(
`ALL TESTS EXECUTION TIME: ${Math.floor(duration)}m${Math.round((duration % 1) * 60)}s`,
);
const file = fs.readFileSync('reporting/results.json', 'utf-8');
// #ts-ignore
const xml = cucumberJunit(file);
fs.writeFileSync('e2e/reporting/results.xml', xml);
fs.rmdirSync(reportingPath, { recursive: true });
},
};
Hi Try declaring your tags like this, if that helps
cucumberOpts: {
tags: '#Smoke,#Intgr'
}
I am able to call baseUrl from one page object file but i am not able to call schoolUrl from another page object file. I am trying to call url from config file without adding whole url in page object file.
My config.js file is
exports.config = {
allScriptsTimeout: 11000,
restartBrowserBetweenTests: true,
specs: [
'./e2e/**/*.e2e-spec.ts'
],
framework: 'jasmine2',
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
args: ["--start-maximized", "--window-size=1630,963"]
}
},
directConnect: true,
port: null,
baseUrl: 'https://class.com',
schoolUrl: 'https://school.com'
}
my page object file to call baseUrl
import {browser, by, element, ElementFinder, ExpectedConditions, promise} from 'protractor';
export class SchoolPage {
public staffUrl = '';
public async navigateTo(): Promise<any> {
return browser.get(``) ;
}
How can i call schoolUrl from config.js file like base url is called directly without adding url in po file
If you add this to your config
exports.config = {
allScriptsTimeout: 11000,
restartBrowserBetweenTests: true,
specs: [
'./e2e/**/*.e2e-spec.ts'
],
framework: 'jasmine2',
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
args: ["--start-maximized", "--window-size=1630,963"]
}
},
directConnect: true,
port: null,
baseUrl: 'https://class.com',
params: {
schoolUrl: 'https://school.com'
},
}
then you can refer to that variable in your code like this browser.params.schoolUrl
Locally my download e2e works fine, my firefox preferences in conf.js correctly disable the browser specific download-popup.
When jenkins runs the test (Jenkins runs on a linux OS, locally I am on macOS), the firefox download-popups aren't disabled.... as the file is never really downloaded.
Also, we are using a custom protracor reporter to make videos of the e2e tests.
See the relevant code below:
conf.js
multiCapabilities: [
{
browserName: 'chrome',
'goog:chromeOptions': {
args: ['--no-sandbox', '--user-data-dir=/tmp']
w3c: false, // problems with latest chrome driver... browser.actions is causing issues: https://github.com/jan-molak/serenity-js/issues/329
prefs: {
download: {
directory_upgrade: true,
prompt_for_download: false,
default_directory: downloadsPath,
},
},
},
},
{
browserName: 'firefox',
marionette: true,
'moz:firefoxOptions': {
args: ['--headless'],
prefs: {
'pdfjs.disabled': true,
'browser.download.folderList': 2,
'browser.download.dir': downloadsPath,
'browser.download.panel.shown': false,
'browser.download.useDownloadDir': true,
'browser.download.manager.useWindow': false,
'browser.helperApps.alwaysAsk.force': false,
'browser.helperApps.neverAsk.openFile': true,
'browser.download.manager.closeWhenDone': false,
'browser.download.manager.alertOnEXEOpen': false,
'browser.download.manager.showWhenStarting': false,
'browser.download.manager.focusWhenStarting': false,
'browser.download.manager.showAlertOnComplete': false,
'browser.helperApps.neverAsk.saveToDisk': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document, '
+ 'application/json, application/vnd.openxmlformats, '
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
},
},
},
],
onPrepare: async () => {
browser.driver.manage().window().setSize(1400, 1200);
browser.waitForAngularEnabled(false);
const caps = await browser.driver.getCapabilities();
// eslint-disable-next-line no-console
console.log('Browser capabilities: %o', caps);
const specReporter = new ProtractorReporter();
jasmine.getEnv().addReporter(specReporter);
},
download-contract.js
const downloadBtn = manipulations.getDomObject('download-contract-button', 'id');
browser.executeScript('arguments[0].click();', downloadBtn.getWebElement());
browser.sleep(5000);
try {
await downloads.verifyFileExists(`mandatierung_${mandateId}.docx`);
const fileSize = await downloads.verifyFileSize(`mandatierung_${mandateId}.docx`);
expect(fileSize).toBeGreaterThan(0);
} catch (err) {
throw new Error(`ERROR: ${err.message}`);
}
downloads.removeFile(`mandatierung_${mandateId}.docx`);
jenkinsfile... this is how the tests are initiated
sh 'protractor-recorder -b=firefox,chrome -r=1400x1280 -p="--suite full" -f=specs/conf.js -o=/tmp/video-out'
I'm trying to write some visual tests and running into the mentioned error with the protractor-image-comparison of version 2.0.1. Even though there is an update of the library I decided to stick to the older version since I experience some issues with the newest one as well.
My setup is:
//protractor.conf.js:
const { SpecReporter } = require('jasmine-spec-reporter');
const { join } = require('path');
const { ProtractorImageComparison } = require('protractor-image-comparison');
exports.config = {
allScriptsTimeout: 11000,
specs: ['./src/**/*-spec.ts'],
capabilities: {
browserName: 'chrome',
chromeOptions: {
args: [
// '--headless',
'--disable-gpu', '--window-size=1600,950', '--no-sandbox'],
},
},
SELENIUM_PROMISE_MANAGER: false,
directConnect: true,
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {
},
},
onPrepare() {
require('ts-node').register({
project: join(__dirname, './tsconfig.e2e.json'),
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
browser.protractorImageComparison = new ProtractorImageComparison({
baselineFolder: join(__dirname, '/src/resources/baseline/'),
screenshotPath: join(__dirname, '/src/tmp/'),
formatImageName: '{tag}',
autoSaveBaseline: false
});
},
};
I came across this issue today and apparently from version 3.0.1 this package now functions as a plugin and not a class which needs to be instantiated.
I managed to get it working adding the following code to my conf.js:
plugins: [
{
inline: require('protractor-image-comparison'),
// package: 'protractor-image-comparison' //protractor is installed globally so it is checking for plugin globally also
options: {
baselineFolder: './testArtifacts/screen-compare/baselines/',
screenshotPath: './testArtifacts/screen-compare/screenshots/',
formatImageName: `{tag}-{logName}-{width}x{height}`,
savePerInstance: true,
},
},
],
Note: For me protractor was installed globally so I needed this workaround using inline instead of package to get it searching for the plugin module locally.
I have a problem, I want to make my test stop in the middle
of the execution of "IT", so proceeding to the next "IT". I've found two ways to do this, one using pending () or fail (), however I want to do something like that, but instead of returning it "pending" or "fail" to return success.
Suite testing
const URLs = 'https://www.google.com/';
const searchGoogle = 'music eletronic youtube';
const searchYoutube = 'nerdologia';
describe('Start simulator False', () => {
it('Enter youtube ', () => {
browser.driver.get(URLs);
browser.sleep(5000);
browser.driver.findElement(by.name('q')).sendKeys(searchGoogle);
browser.driver.findElement(by.xpath('/html/body/div/div[3]/form/div[2]/div/div[3]/center/input[1]')).click();
browser.sleep(1000);
// browser.pause();
browser.driver.findElement(by.xpath('//*[#id="rso"]/div/div/div[2]/div/div/div[1]/a')).click();
isAngularSite(false);
});
it('Search to data random youtube', () => {
browser.sleep(6000);
element(by.id('search')).sendKeys(searchYoutube).then((visible) => {
if (visible) {
throw 'Error';
}
element(by.id('search-icon-legacy')).click();
});
// browser.driver.findElement(by.css('[#search]')).sendKeys(searchYoutube);
browser.sleep(6000);
browser.driver.findElement(by.xpath('//*[#id="contents"]/ytd-video-renderer[1]')).click().then(() => {
throw 'Stop the test';
});
browser.sleep(6000);
browser.executeScript('document.querySelector(\'#movie_player > div.html5-video-container > video\').pause();');
});
})
Protractor.conf.js
const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
const AllureReporter = require('jasmine-allure-reporter');
exports.config = {
// The address of a running selenium server.
seleniumAddress: 'http://localhost:4444/wd/hub',
// Spec patterns are relative to the location of this config.
specs: [
'webapp/e2e/spec/*.js',
],
capabilities: {
browserName: 'chrome',
shardTestFiles: true,
maxInstances: 5,
marionette: true,
acceptInsecureCerts: true,
chromeOptions: { args: ['--disable-extensions'] },
// browserName: 'chrome',
// chromeOptions: {
// args: ['--no-sandbox', '--disable-dev-shm-usage',
// "--headless", "--disable-gpu", "--window-size=1366x768" ]
// }
},
// capabilities: {
// directConnect: true,
// browserName: 'chrome',
// marionette: true,
// acceptInsecureCerts: true,
// chromeOptions: {
// args: ['--no-sandbox', '--disable-dev-shm-usage',
// '--headless', '--disable-gpu', '--window-size=800x600'],
// },
// },
// capabilities: {
// 'browserName': 'chrome',
// 'chromeOptions': {'args': ['--disable-extensions']}
// // browserName: 'chrome',
// //
// // chromeOptions: {
// // args: [ "--headless", "--disable-gpu", "--window-size=800,600" ]
// // }
// },
onPrepare() {
global.isAngularSite = function (flag) {
browser.ignoreSynchronization = !flag;
};
jasmine.getEnv().addReporter(new SpecReporter({
displayFailuresSummary: true,
displayFailuredSpec: true,
displaySuiteNumber: true,
displaySpecDuration: true,
}));
jasmine.getEnv().addReporter(new AllureReporter({
resultsDir: 'allure-results',
}));
jasmine.getEnv().afterEach((done) => {
browser.takeScreenshot().then((png) => {
allure.createAttachment('Screenshot', () => new Buffer(png, 'base64'), 'image/png')();
done();
});
});
beforeEach(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1800000;
});
afterEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
},
allScriptsTimeout: 180000,
getPageTimeout: 180000,
jasmineNodeOpts: {
onComplete: null,
isVerbose: false,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 1800000,
},
};
how to run faster
protractor protractor.conf.js --specs='nameOfFile.js'
Protractor uses the Jasmine testing framework out of the box.
Jasmine allows for the testFunction passed in a Specs to be declared to receive a callback.
Even so that your test is synchronous, converting it to an asynchronous one allows for you to control when Jasmine moves one to the next test.
You can use this to let Jasmine know to move on by invoking this argument. e.g.
it('Enter youtube ', (done) => {
// some operations that you care about running
done();
// other operations that you like to skip
});