Time out error when using browser.getCurrentUrl() after URL changes - protractor

I am writing a protractor test for login for an AngularJS app and want to verify that the login is successful and the url changes after login. I tried to use Expected condition with urlContains() and also tried with browser.getCurrentUrl().toContain() but I am getting error in both.
exports.config = {
seleniumAddress : 'http://localhost:4444/wd/hub',
specs: ['login.spec.js'],
};
Expected condition passes the test when the url is correct. But when the url is different then it throws timeout error
"Failed: Wait timed out after 5013ms".
expect(browser.getCurrentUrl()).toContain('/dashboard') fails always with below error
Stack:
ScriptTimeoutError: script timeout: result was not received in 11 seconds
(Session info: chrome=75.0.3770.142)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.3', java.version: '12.0.1'
Driver info: driver.version: unknown
at Object.checkLegacyResponse (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/error.js:546:15)
at parseHttpResponse (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/http.js:509:13)
at doSend.then.response (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/http.js:441:30)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
From: Task: Protractor.waitForAngular()
at thenableWebDriverProxy.schedule (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver.js:807:17)
at ProtractorBrowser.executeAsyncScript_ (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/built/browser.js:425:28)
at angularAppRoot.then (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/built/browser.js:456:33)
at ManagedPromise.invokeCallback_ (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:1376:14)
at TaskQueue.execute_ (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:3084:14)
at TaskQueue.executeNext_ (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:3067:27)
at asyncRun (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2927:27)
at /Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:668:7
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
From: Task: Run it("should login successfully") in control flow
at UserContext.<anonymous> (/Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/jasminewd2/index.js:94:19)
From asynchronous test:
Error
at Object.<anonymous> (/Users/ProtractorTest/Tests/login.spec.js:17:3)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at /Users/.nvm/versions/node/v8.9.4/lib/node_modules/protractor/node_modules/jasmine/lib/jasmine.js:93:5
Below is my code
it('should login successfully', function () {
browser.get("https://example.com/");
loginobj.username.sendKeys(logindata.email);
loginobj.password.sendKeys(logindata.password);
loginobj.loginbtn.click().then(function(){
browser.getCurrentUrl().then(url => expect(url).toContain('/dashboard'));
//var EC = protractor.ExpectedConditions;
//browser.wait(EC.urlContains('/dashboard'), 5000);
})
I expect that when the url is different than the expected one, it should display a valid error message instead of timeout error.

By default protractor handles all the asynchrony for you. Looking at your code you are relying on default protractor behaviour i.e. not setting SELENIUM_PROMISE_MANAGER to false.
In that case, why do you want to do something inside click().then() ? It can be as simple and plain as
loginobj.loginbtn.click();
expect(browser.getCurrentUrl()).toContain('/dashboard');
One theory with your code: once you have something inside click().then(), its out of place from the promise queue that protractor is handling for you. Unless it is absolutely necessary, for ex get value from an element for later use in the spec, I would suggest not to meddle with protractor asynchronous handling as much as possible.
Hope that helps.

I have something similar
const currentUrl = await browser.getCurrentUrl().then(url => url);
expect(currentUrl).toContain('/dashboard')
Try it out maybe it will help, just without await as i see you don't use async functions
or like this
await browser.getCurrentUrl().then(url => expect(url).toContain('/dashboard'));

In protractor default script time out is 11 seconds,
In above code snippet,
browser.getCurrentUrl().then(url => expect(url).toContain('/dashboard'));
statement takes more than 11 seconds to resolve promise.
Solution: In Protractor configuration file, add below statements
allScriptsTimeout: timeout_in_millis.
e.g for 30 second timeout
allScriptsTimeout: 30000
Edited Configuration File:
exports.config = {
allScriptsTimeout: 30000,
seleniumAddress : 'http://localhost:4444/wd/hub',
specs: ['login.spec.js'],
};

Related

Issue in export and import ES6 Classes in protractor testing

I'm facing two issues while using ES6 class export and import. First, while import, methods cannot be accessible from imported class. Second, while executing the code through visual studio code im facing the following error "SyntaxError: Unexpected token import". Please provide correction or suggestion.
Below are my my class file "Login_pageobj.js"
export default class Login_pageobj {
constructor() {
//userName
this.enterUserName = element(by.xpath('//input[#id="username"]'));
//Password
this.enterPassword = element(by.xpath('//input[#id="password"]'));
//Login Button
this.clickLoginBtn = element(by.buttonText('LOGIN'));
//invalid UserName Password Error
this.inValErrMsg = element(by.xpath('//div[#class="subtext"]'));
}
//Please enter a user name (required). method
isDisplyedUserNameErrorMsg() {...}
This below code is My Protractor spec file Login_spec.js
import Login_pageobj from '../ES6_pageobj/login_pageobj';
describe('Login Page Validation', function() {
it('Launch Commercial URL',function(){
browser.get('http://applicationurl');
browser.manage().window().maximize();
expect(browser.getTitle()).toBe('LoginWeb');
});
it('Login Button should Disabled',function(){
console.log('----------------------------------------------------');
let lgin_pgobj = new login_pageobj();
lgin_pgobj.verifyLgnBtnEnabled();//***unable to access this method***
});
});
While run this code through Visual studio code debugger i'm getting following error.
Debugging with inspector protocol because Node.js v8.9.1 was detected.
node --inspect-brk=23169 node_modules\protractor\bin\protractor
e:\CommercialPOC/conf.js --suite es6
Debugger listening on ws://127.0.0.1:23169/e3dfd326-8468-4a3a-a2e3-3094d97c5571
(node:4708) [DEP0022] DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
(node:4708) [DEP0022] DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
warning.js:18
[22:00:06] I/launcher - Running 1 instances of WebDriver
logger.js:155
[22:00:06] I/direct - Using ChromeDriver directly...
logger.js:155
null
conf.js:48
[22:00:25] E/launcher - Error:
e:\commercialPOC\ES6_moduleScenarios\0Login_spec.js:1
logger.js:155
(function (exports, require, module, __filename, __dirname) { import
Login_pageobj from '../ES6_pageobj/login_pageobj';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:599:28)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at e:\CommercialPOC\node_modules\jasmine\lib\jasmine.js:93:5
[22:00:25] E/launcher - Process exited with error code 100
You should use such import constructure:
const Login_pageobj = require('../ES6_pageobj/login_pageobj')

'Globals' are not working as expected in protractor 4.0.0?

we have the following setting in our onPrepare function of config file-
exports.config = {
directConnect: true,
baseUrl: env.baseUrl,
capabilities: env.capabilities,
onPrepare: function () {
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
global.expect = chai.expect; // by removing this line error is not thrown
browser.manage().window().maximize();
},
setDefaultTimeout : 60 * 1000,
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
specs: [
'../Features/*.feature'
],
cucumberOpts: {
monochrome: true,
strict: true,
plugin: ["pretty"],
require: ['../StepDefinitions/*.js', '../Support/*.js'],
tags:'#AddActiveTip,#AddInActiveTip,~#AddActiveManufacturer,~#AddInActiveManufacturer'
//tags:'#TestSplitText'
}
};
since the upgrade to protractor 4.0, I am getting the following error and the browser hangs indefinitely and the error does not help to debug in anyway.
error:
> protractor Config/config.js --troubleshoot
[22:38:12] I/direct - Using FirefoxDriver directly...
[22:38:12] I/launcher - Running 1 instances of WebDriver
/Users/pasalar/protractor/psms-protractor/node_modules/protractor/built/exitCodes.js:87
if (e.message.indexOf(errMsg) !== -1) {
^
TypeError: Cannot read property 'indexOf' of undefined
at Function.ErrorHandler.isError (/Users/pasalar/protractor/psms-protractor/node_modules/protractor/built/exitCodes.js:87:30)
at Function.ErrorHandler.parseError (/Users/pasalar/protractor/psms-protractor/node_modules/protractor/built/exitCodes.js:98:26)
at process.<anonymous> (/Users/pasalar/protractor/psms-protractor/node_modules/protractor/built/launcher.js:169:54)
at emitOne (events.js:82:20)
at process.emit (events.js:169:7)
at process.emit (/Users/pasalar/protractor/psms-protractor/node_modules/protractor/node_modules/source-map-support/source-map-support.js:419:21)
at process._fatalException (node.js:224:26)
npm ERR! Test failed. See above for more details.
is anyone else facing this issue? are there any major changes that I am missing?
The error message shown has nothing to do with "globals", it is working as expected! my scripts were failing randomly due to network latency issues.But the error messages need to improved as the user has no idea what caused the error!
Marking it closed as I was able debug this issue!

Error on protractor: "Timed out waiting for the WebDriver server at http://127.0.0.1:50636/hub" executing on firefox

I was executing my scripts on firefox and got one notification for Firefox upgrade which I closed. Started execution again but I'm getting error as below,
Rohits-MacBook-Pro:FFAutomation rohitgathibandhe$ /Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/bin/protractor conf.js
Report destination: target/screenshots/Report.html
Using FirefoxDriver directly...
[launcher] Running 1 instances of WebDriver
/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/selenium-webdriver/http/util.js:83
Error('Timed out waiting for the WebDriver server at ' + url));
^
Error: Timed out waiting for the WebDriver server at http://127.0.0.1:50636/hub
at Error (native)
at onError (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/selenium-webdriver/http/util.js:83:11)
at Promise.invokeCallback_ (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:1329:14)
at TaskQueue.execute_ (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2790:14)
at TaskQueue.executeNext_ (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2773:21)
at /Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2652:27
at /Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:639:7
at process._tickCallback (node.js:406:9)
From: Task: WebDriver.createSession()
at acquireSession (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver.js:62:22)
at Function.createSession (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver.js:295:12)
at Driver (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/selenium-webdriver/firefox/index.js:271:38)
at [object Object].DirectDriverProvider.getNewDriver (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/built/driverProviders/direct.js:76:16)
at [object Object].Runner.createBrowser (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/built/runner.js:203:37)
at /Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/built/runner.js:293:21
at _fulfilled (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/q/q.js:834:54)
at self.promiseDispatch.done (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/q/q.js:863:30)
at Promise.promise.promiseDispatch (/Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/q/q.js:796:13)
at /Users/rohitgathibandhe/npm-global/lib/node_modules/protractor/node_modules/q/q.js:556:49
[launcher] Process exited with error code 1
My config file is as below,
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var reporter = new HtmlScreenshotReporter({
dest: 'target/screenshots',
filename: 'Report.html',
reportTitle: 'Execution Report',
showSummary: true,
showQuickLinks: true,
pathBuilder: function(currentSpec, suites, browserCapabilities) {
// will return chrome/your-spec-name.png
return browserCapabilities.get('browserName') + '/' + currentSpec.fullName;
}
});
exports.config = {
directConnect: true,
//seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: {'browserName': 'firefox'},
framework: 'jasmine',
specs: ['Login_spec2.js','Article_spec.js'],
allScriptsTimeout: 200000,
getPageTimeout: 200000,
jasmineNodeOpts: {
defaultTimeoutInterval: 200000
},
// Setup the report before any tests start
beforeLaunch: function() {
return new Promise(function(resolve){
reporter.beforeLaunch(resolve);
});
},
// Close the report after all tests finish
afterLaunch: function(exitCode) {
return new Promise(function(resolve){
reporter.afterLaunch(resolve.bind(this, exitCode));
});
},
onPrepare: function() {
var width = 1300;
var height = 1200;
browser.driver.manage().window().setSize(width,height);
jasmine.getEnv().addReporter(reporter);
afterAll(function(done) {
process.nextTick(done);
})
}
};
Other details are:
Other details are as below: protractor#3.2.2, nodeVersion: 4.2.4, npmVersion: 2.14.12, jasmine: 2.4.1, selenium-webdriver: 2.52.0, firefox: 47
Kindly help me with solution to this issue.
You have to do the following to make it work:
upgrade protractor to the latest, currently 3.3.0, version which would also bring selenium-webdriver 2.53
downgrade firefox to version 46 and don't let it update for a while (there are compatibility issues)
In my case it was the local firewall (iptables on Linux) that was very restrictive such that WebDriver could not contact the Selenium server hub at whatever TCP port.
To make it work I turned off the firewall. The long term solution was to adjust the firewall rules such that this type of connection is allowed.
If you want your scripts communicate directly with the Firefox|Chrome Driver (bypassing the Selenium server entirely) then try adding the directConnect: true in your protractor.conf.js
I solved it by change the browser (use Chrome instead of Firefox).
In C:__projectWorkspace__\src\test\javascript\protractor.conf.js
modify the entry
capabilities: {
'browserName': 'firefox',
to
capabilities: {
'browserName': 'chrome',
That wasn't enough. I had to change also the webBrowserDriver 'cause after the JHipster installation the 2.22 version was written in protractor.conf.js file but in the path:
node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.25.exe
the chromedriver was 2.25 version so i edited the entry
webbrowserDriver = prefix + 'node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.25.exe';
and it worked!
I solved this by restarting the computer.
I don't know why, but I think that "suspending" the computer can cause some bad configuration with Selenium Server.
Ah, I run commands on the command prompt as an administrator.
I fixed this issue by changing directConnect to true in base.config.js from repository folder.
or
webdriver-manager clean and then webdriver-manager start

selenium standalone terminates with unknown error

when i start my test the browser opens and an ip is displayed after few sec the ip is changed to "data;" in terminal the test is been looped and sends err ms
empresss-Mac-mini:myApp admin$ protractor test/e2e.js
Using the selenium server at http://localhost:4444/wd/hub
[launcher] Running 1 instances of WebDriver
Started
A Jasmine spec timed out. Resetting the WebDriver Control Flow.
F
Failures:
1) header Module should check title text
Message:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
Stack:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
Message:
Failed: header is not defined
Stack:
ReferenceError: header is not defined
at Object.<anonymous> (/Users/admin/myApp/www/head.spec.js:8:13)
From: Task: Run it("should check title text") in control flow
From asynchronous test:
Error
at Suite.<anonymous> (/Users/admin/myApp/www/head.spec.js:7:4)
at Object.<anonymous> (/Users/admin/myApp/www/head.spec.js:1:63)
1 spec, 1 failure
Finished in 30.019 seconds
[launcher] 0 instance(s) of WebDriver still running
[launcher] chrome #1 failed 1 test(s)
[launcher] overall: 1 failed spec(s)
[launcher] Process exited with error code 1
my config file is
exports.config = {
framework: 'jasmine2',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['../www/head.spec.js'],
multiCapabilities: [
{
browserName: 'chrome'
}],
onPrepare: function(){
browser.driver.get('http://192.168.1.2:8100');
}
}
i named it as e2e.js
my test file is
describe('header Module', function(){
beforeEach(function() {
var header = element(by.css('title'));
});
it('should check title text',function(){
expect(header.getText()).toContain('Ionic Blank Starter');
});
});
i downloaded an blank ionic app and i want to test the header contains elements "Ionic Blank Starter"
You are not handling async code well in your project. header.getText() returns a promise which you need to resolve before asserting the text. You can do something like this:
describe('header Module', function(){
it('should check title text',function(callback){
var header = element(by.css('.title'));
header.getText()
.then(function (text) {
expect(text).toContain('Ionic Blank Starter');
callback();
});
});
});

Keystone and openshift, getting 503 error

Can anyone please help me install keystone.js on my openshift app?
I've pushed all my files to the remote, but get a 503 error when I browse to my page. I'm quite new to Openshift, can anyone please point me in the right direction?
I have tried changing keystone.init to:
var connectionString = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" + process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "#" + process.env.OPENSHIFT_MONGODB_DB_HOST + dbName;
console.log(connectionString);
keystone.set('mongo', connectionString);
keystone.init({
'mongo': connectionString,
Still no joy, I dont get any console errors either.
Any advice much appreciated.
UPDATE: checked logs and found the following:
SyntaxError: Unexpected end of input
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/var/lib/openshift/5501b0c04382ecfefe0000a2/app-root/runtime/repo/node_modules/keystone/index.js:3:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
DEBUG: Program node keystone.js exited with code 8
DEBUG: Starting child process with 'node keystone.js'
hit me
/var/lib/openshift/5501b0c04382ecfefe0000a2/app-root/runtime/repo/node_modules/underscore/underscore.js:561
});
SyntaxError: Unexpected end of input
at Module._compile (module.js:439:25)
Keystone.js
// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
// Require keystone
var keystone = require('keystone');
// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.
var dbName = "node";
var connectionString = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" + process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "#" + process.env.OPENSHIFT_MONGODB_DB_HOST + dbName;
console.log(connectionString);
keystone.set('mongo', connectionString);
keystone.init({
'mongo': connectionString,
'name': 'node',
'brand': 'node',
'sass': 'public',
'static': 'public',
'favicon': 'public/favicon.ico',
'views': 'templates/views',
'view engine': 'jade',
'auto update': true,
'session': true,
'auth': true,
'user model': 'User',
'cookie secret': '^<S0$!?a778,)~[Fx4wQvgcTw]fWq.)<s`cAJc:bExU*(L&ty9;mSV?`am:*7f.P'
});
// Load your project's Models
keystone.import('models');
// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
keystone.set('locals', {
_: require('underscore'),
env: keystone.get('env'),
utils: keystone.utils,
editable: keystone.content.editable
});
// Load your project's Routes
keystone.set('routes', require('./routes'));
// Setup common locals for your emails. The following are required by Keystone's
// default email templates, you may remove them if you're using your own.
// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
'posts': ['posts', 'post-categories'],
'enquiries': 'enquiries',
'users': 'users'
});
// Start Keystone to connect to your database and initialise the web server
keystone.start();
Fixed this by making sure all node modules were on the server, pushing to the repo using sourcetree kept timing out, so the modules weren't there. I FTP'd them instead.