I've been looking at the documentation for protractor and I want to be able to select an array of via a selector of any sort and get the text value of the first one and assert it. No matter what I try with protractor it times out when I try getText() and get().
This is what I'm looking at. Reference
Here is my code:
describe('E2E: Global Scan', function () {
beforeEach(function () {
browser.get('#/dashboard/global-scan');
});
it('should grab all a tags within li tags', function () {
element.all(by.css('li a')).then(function(items) {
expect(items.length).toBeDefined()
expect(items[0].getText()).toBeDefined();
});
var list = element.all(by.css('li a'));
expect(list.length).toBeDefined()
expect(list.get(0).getText()).toBeDefined();
});
});
As you can see I tried both with a then promise function and save the result of element.all to a variable and looping through that. That doesn't work either. What happens is the test just times out.
Failures:
1) E2E: Global Scan should grab all a tags within li tags Message:
Error: Timed out waiting for Protractor to synchronize with the page after 10 seconds. Please see
https://github.com/angular/protractor/blob/master/docs/faq.md
If I try browser.element that starts to return me something. But it still breaks when I use get or getText().
Does anyone have any ideas? Doing what the documentation says doesn't actually work. Do I have a really old version of protractor?
You can increase that with setting protractor config
allScriptsTimeout: timeout_in_millis
Refer the https://github.com/angular/protractor/blob/master/docs/timeouts.md page Waiting for Page Synchronization topic for more info.
I was facing the same issue while doing E2E for Angular Project.
Finally, I configured the protractor.conf.js file and spec.e2e.ts to get rid of "Times Out Waiting For Element
".
protractor.conf.js
const { SpecReporter } = require('jasmine-spec-reporter')
exports.config = {
allScriptsTimeout: 110000,
getPageTimeout: 110000,
specs: [
'./e2e/**/example.e2e-spec.ts',
],
capabilities: {
browserName: 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:8123/',
framework: 'jasmine',
jasmineNodeOpts: {
showTiming: true,
showColors: true,
includeStackTrace: false,
defaultTimeoutInterval: 600000
},
onPrepare () {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
})
browser.driver.manage().deleteAllCookies();
browser.driver.manage().window().maximize();
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
}
example.e2e-spec.ts
import { browser, by, protractor, element, promise, ElementFinder, ElementArrayFinder } from 'protractor';
describe('Test', () => {
var originalTimeout;
beforeEach(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 120000;
browser.driver.sleep(3000);
});
afterEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
browser.driver.sleep(5000);
});
it('It should display title and it should login also',() => {
browser.ignoreSynchronization = true;
browser.get('/',5000);
expect(browser.getTitle()).toEqual('TitleExample');
});
});
Related
I am working with protractor and cucumber. I want to print the text returned from getText. I am using .then function to obtain such text, but for some reason, console.log code is not being executed.
Why is this happening?
checkDropdown: function (value, dropdown) {
let name = element(by.id(dropdown));
name.getText().then(function(text){
console.log(text);
});
expect(name.getText()).to.eventually.equal(value);
},
The protractor.conf.js file is:
Protractor file is:
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub', // This is targetting your local running instance of the selenium webdriver
specs: [
'../Features/UI_Tests.feature'
],
capabilities: {
browserName: 'chrome' // You can use any browser you want. On a CI environment you're going to want to use PhantomJS
},
framework: 'custom', //We need this line to use the cucumber framework
frameworkPath: require.resolve('protractor-cucumber-framework'), // Here it is
cucumberOpts: {
//format: 'pretty',
require: '../Features/step_definitions/my_steps.js', // This is where we'll be writing our actual tests
//tags: ['#login','#app'],
strict: true,
plugin:"json"
},
resultJsonOutputFile:'./testResults.json', //output file path to store the final results in .json format
params: {
env: {
hostname: 'http://0.0.0.0:8000' // Whatever the address of your app is
}
}
};
Thanks in advance.
May be the text value which you log is blank.
Can you try adding some test in front of your text
name.getText().then((text)=>{
console.log('Text value is' + text);
});
Just to check if console.log is executed.
This is error message on a protractor test use protractor http mock:
JavascriptError: javascript error: [$injector:nomod] Module 'httpMock'
is not available! You eit her misspelled the module name or forgot to
load it. If registering a module ensure that you specify the
dependencies as the second argument.
conf.js:
// An example configuration file.
exports.config = {
directConnect: true,
// Selenium server
SeleniumAddress: 'http://localhost:4444/wd/hub',
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
//baseUrl: 'http://develop.garbo.livebranches.com/sv-SE/',
//Framework to use. Jasmine 2 is recommended.
framework: 'jasmine2',
//frameworks: ['mocha', 'jasmine'],
// Spec patterns are relative to the current working directly when
// protractor is called.
//specs: ['testmain.js','testlogin.js'],
//specs: ['testmain.js','testteaPartyList.js','testpositionSearchIndex.js','testpositionList.js'],
specs: ['testlogin.js'],
//Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 250000
},
mocks: {
dir: '../node_modules/protractor-http-mock',
//dir: 'mocks',
default: []
},
//=====login begin =====
onPrepare: function() {
require("protractor-http-mock").config = {
rootDirectory: '../node_modules/protractor-http-mock/lib',
//rootDirectory: __dirname,
protractorConfig: "conf.js", // name of the config here
};
}
//=====login end========
};
testlogin.js
describe('angularjs homepage', function() {
//browser.ignoreSynchronization = true;
it('should login', function() {
var mock = require('protractor-http-mock');
var todoList;
beforeEach(function() {
var url ='http://dev.etest.com:285/Actor/tbUsers/LoginAndGet';
var req = {Mobile:'14500000006',Password:'123456'};
var rep = {UserId:164,AccountId:328,Token:'328:dc91d536ab424aa0b8d7f1ecaf64c55b',Id:328};
mock([{
request: {
path: url,
method: 'POST',
data:req,
},
response: {
data: rep,
}
}]);
});
afterEach(function() {
mock.teardown();
});
browser.get('http://localhost:2024/daNiuJob/www/ionicWeb/index.html#/login');
console.log('mock='+mock);
element(by.model('data.userName')).sendKeys('14500000006');
element(by.model('data.password')).sendKeys('123456');
var btnlogin = element(by.id('Regist')).element(by.tagName('a'));
expect(browser.getTitle()).toEqual('userlogin');
browser.getTitle().then(function(text){
console.log('title='+text);
});
//cause mock error
expect(mock.requestsMade()).toEqual([
{ url : 'http://dev.etest.com:285/Actor/tbUsers/LoginAndGet', method : 'GET' },
]);
btnlogin.click();
browser.sleep(8000);
});
});
Why can't find httpMock, thank!
note:
C:\Users\HQ-XXX\AppData\Roaming\npm\node_modules\protractor\node_modules\protractor-http-mock
This is path of 'protractor-http-mock'
You should be giving the path of the http-mock module folder and not lib folder inside it. Change your rootDirectory path of protractor-http-mock inside onPrepare() function to -
rootDirectory: 'C:\Users\HQ-XXX\AppData\Roaming\npm\node_modules\protractor\node_modules\protractor-http-mock ',
If at all you need to provide a relative path then change it as below -
rootDirectory: '..\node_modules\protractor-http-mock ',
Hope this helps.
We had the same issue and it was related to the page reloading at the beginning of every spec.
This was caused by a faulty config of html5mode and the browser.get so it did a redirect at the beginning from foo.bar/ to foo.bar/#/ which unloads all injected protractor code.
In protractor I search for a LinkText Login thats worked fine. I were redirect to the login site (non angular) and type in the username and pw. Clicking the submit button i came back to the first site. Now the Login Button is a Logout button. But protractor cannot see a angular site I only can find the button with selenium indicators.
The spec.js file:
it ('should have a login Button to click', function() {
loginPage.clickLoginButton();
});
it('should be on idm to login', function() {
var url = browser.driver.getCurrentUrl();
expect( url ).toEqual('http://localhost/webapp/login');
});
it('should have access with the given user', function() {
var idmPage = require('./idmPage.js');
idmPage.setUsername('bla');
idmPage.setPassword('secret');
idmPage.clickSubmitButton();
});
The pageobject.js:
var IdmPage = function() {
var userField = browser.driver.findElement(by.id('id_login'));
var passwordField = browser.driver.findElement(by.id('id_password'));
var submitButton = browser.driver.findElement(by.id('authentication-button'));
this.setUsername = function(username) {
userField.sendKeys(username);
};
this.setPassword = function(password) {
passwordField.sendKeys(password);
};
this.clickSubmitButton = function() {
submitButton.click();
}; }; module.exports = new IdmPage();
The conf.js
'use strict';
var baseDir = 'test/e2e';
exports.config = {
// The adress of a runnung selenium server.
seleniumAddress: 'http://localhost:4444/wd/hub',
//Capabilities to be passed to the webdirver instance.
capabilities: {
browserName: 'chrome'
},
//Spec patterns are relative to the current working directly when protractor is called
suites: {
login: baseDir + '/login/**/*_spec.js',
content: [baseDir + '/content/*_spec.js']
},
//Options to be passed to Jasmine-node
jasmineNodeOpts: {
onComplete: null,
isVerbose: true,
showColors: true,
includeStackTrace: false,
defaultTimeoutInterval: 11000
}
};
You may want to make sure that protractor is actually waiting for your inputs to load when switching between non-angular and angular pages. So did you try using a browser.sleep() or browser.wait() after clicking the submit button? You should set browser.ignoreSynchronization = true; when testing non-angular pages. What is browser.ignoreSynchronization in protractor?
UPDATE:
browser.ignoreSynchronization = true;
this.clickLogoutButton = function(){
browser.wait(function(){
return loginButton.isPresent();
}, 10000).then(function(){
loginButton.click();
});
}
this way your test will wait a maximum of 10 seconds before the test times out. You can update this depending on how long it should take at maximum before the button would appear clickable. This is how i deal with testing my non-angular web-pages. I hope this works for you
I am writing simple protractor test four our application:
login page is without angularhs - working fine
all other pages are with angularjs
When i want to write angularhs test - i got this error (following this installation) :
Timed out waiting for Protractor to synchronize with the page after 40002ms. Please see https://github.com/angular/protractor/blob/master/docs/faq.md
Config:
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['login-spec.js'],
baseUrl: 'https:/xyz/',
allScriptsTimeout: 40000,
capabilities: {
'browserName': 'firefox'
}
}
And my spec:
describe('Login #1', function() {
// BEFORE LOGIN
it('should pass to next login step', function() {
browser.driver.get('https://xyz/login');
browser.driver.findElement(by.css(".factorFirst > [name='username']:first-child")).sendKeys('123456');
.... other login stuff
}, 90000);
// AFTER LOGIN TEST
it('Simple Angular Test', function() {
browser.get('/page');
element(by.model('payment.userSpecified.message')).sendKeys(1);
}, 45000);
});
We don't have in our body element attribute ng-app. Can this be a problem?
You need to let protractor know that the login page is non-angular and it doesn't need to wait for angular to "settle down". Set the ignoreSynchronization to true before login and set it back to false after:
describe('Login #1', function() {
afterEach(function () {
browser.ignoreSynchronization = false;
});
it('should pass to next login step', function() {
browser.ignoreSynchronization = true;
browser.driver.get('https://xyz/login');
browser.driver.findElement(by.css(".factorFirst > [name='username']:first-child")).sendKeys('123456');
}, 90000);
it('Simple Angular Test', function() {
browser.get('/page');
element(by.model('payment.userSpecified.message')).sendKeys(1);
}, 45000);
});
Am trying to run firsttest.js:
// firsttest.js
describe('angularjs homepage', function() {
var firstNumber = element(by.model('first'));
var secondNumber = element(by.model('second'));
var goButton = element(by.id('gobutton'));
var latestResult = element(by.binding('latest'));
beforeEach(function() {
browser.get('http://juliemr.github.io/protractor-demo/');
});
it('should have a title', function() {
expect(browser.getTitle()).toEqual('Super Calculator');
});
it('should add one and two', function() {
firstNumber.sendKeys(1);
secondNumber.sendKeys(2);
goButton.click();
expect(latestResult.getText()).toEqual('3');
});
it('should add four and six', function() {
// Fill this in.
expect(latestResult.getText()).toEqual('10');
});
it('test1', function() {
// Fill this in.
expect(true).toEqual(true);
});
it('test2', function() {
// Fill this in.
expect(true).toEqual(true);
});
it('test3', function() {
// Fill this in.
expect(true).toEqual(true);
});
});
conf file:
var HtmlReporter = require('protractor-html-screenshot-reporter');
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['firsttest.js'],
multiCapabilities: [{
'browserName': 'chrome'
}],
onPrepare: function() {
// Add a screenshot reporter and store screenshots to `/tmp/screnshots`:
jasmine.getEnv().addReporter(new HtmlReporter({
baseDirectory: './e2e-reports',
takeScreenShotsOnlyForFailedSpecs: true,
docTitle: 'Pytheas Tests'
}));
}
}
Console o/p:
Failures:
1) angularjs homepage should add four and six Message:
Expected '0' to equal '10'. Stacktrace:
Error: Failed expectation
at [object Object]. (/Users/bgowda1/Work/Projects/Demos/protractor-tests/firsttest.js:35:36)
Finished in 6.191 seconds 6 tests, 6 assertions, 1 failure
HTML report shows only 5 tests.
I was able to reproduce it - this is always the latest it block that is missing in the final HTML report. This should be reported to the protractor-html-screenshot-reporter bug tracker.
As a current workaround, downgrade to protractor 1.4.0 (tested, worked for me). Or, add an empty it() block to the end of the file. I'll update the post if I'll come up with a fix, or better workaround.