element.getText().then(function) not being executed - javascript

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.

Related

How to change the default log file name and/or location for PhantomJS in WebdriverIO

My test suite uses WebdriverIO and WDIO as the runner to run tests against PhantomJS.
The default location for the phantomjsdriver.log file is the root of the project.
There is an option in wdio.conf.js to pass command line arguments to PhantomJS:
const profiles = {
default: {
services: ['selenium-standalone'],
seleniumLogs: 'logs',
capabilities: [
{
maxInstances: 1,
browserName: 'phantomjs',
'phantomjs.binary.path': phantomjsPath, // Set elsewhere
'phantomjs.cli.args': [
'--debug=true',
'--webdriver-logfile=/project/new/path/phantomjsdriver.log'
]
},
]
},
...
}
This results in the following in selenium-standalone.txt:
17:03:29.589 INFO - arguments: [--debug=true, --webdriver-logfile=/project/new/path/phantomjsdriver.log, --webdriver=33837, --webdriver-logfile=/project/phantomjsdriver.log]
Note that the first --webdriver-logfile value is the one I set, the second is the default which I'm trying to overwrite.
How can I stop that second one being included?

passing value fron conf.js to a grunt task or between grunt tasks

How do I pass information between grunt tasks? I would like to pass a value from a grunt task to another grunt task.
My situation is that after completing a protractor test, I would like to pass a value to a new grunt task. To achieve this, I went ahead and set the value in process.env and tried to use process.env in the new grunt task. But that doesn't seem to work
This is conf.js:
afterLaunch: function(exitCode) {
return new Promise(function(fulfill, reject) {
if (typeof jasmine.getEnv().testReportFilePath !== 'undefined' && jasmine.getEnv().testReportFilePath !== null) {
process.env.testReportFilePath = jasmine.getEnv().testReportFilePath;
console.log('Trying: ' + process.env.testReportFilePath);
fulfill('Success: Environment variable testReportFilePath is set in conf.js');
} else {
reject(new Error('Failed: Environment variable testReportFilePath not set in conf.js'));
}
});
And this is my Gruntfile:
grunt.loadNpmTasks('grunt-protractor-runner');
grunt.loadNpmTasks('grunt-protractor-webdriver');
grunt.loadNpmTasks('grunt-execute');
grunt.config('protractor', {
require: [ setTesting ],
options: {
configFile: 'conf.js', // common config file
keepAlive: true, // If false, the grunt process stops when the test fails.
noColor: false // If true, protractor will not use colors in its output.
},
run_specific_suite: {
options: {
args: {
baseUrl: '<%= grunt.option("testUrl") %>',
browser: '<%= grunt.option("testBrowser") %>',
params: {
environment: '<%= grunt.option("testEnv") %>'
},
suite: '<%= grunt.option("testSuite") %>'
}
}
},
});
grunt.config('execute', {
email_stakeholders: {
options: {
args: [
process.env.testReportFilePath,
'myemail#email.com'
]
},
src: ['toDelete.js']
}
});
But process.env.testReportFilePath appears to be undefined in the gruntjs file.
This answer is long overdue. I did follow #mparnisari suggestion to write the variable out to the file. So I did the following in my conf.js to write the value into a yaml file :
fs.writeFileSync(path.join(process.cwd(),'_testReportFilePath.yml'),
'testReportFilePath: ' + jasmine.getEnv().testReportFilePath);
and in the gruntfile, the yaml file read using the grunt api :
// --- grunt execute task --- //
grunt.config('execute', {
email_stakeholders: {
options: {
args:[
grunt.file.readYAML(path.join(process.cwd(),'_testReportFilePath.yml')).testReportFilePath, // html report
'myemail#email.com'//enter the recipient emails here
]
},
src: ['test/scripts/nightlyPostTasks.js']
}
});
and appears to do what I need. Only quirk is that a dummy yaml file with the name _testReportFilePath.yml must always be present in CWD to prevent any grunt error.

Module 'httpMock' is not available

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\protrac‌​tor-http-mock ',
If at all you need to provide a relative path then change it as below -
rootDirectory: '..\node_modules\protrac‌​tor-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.

protractor-html-screenshot-reporter not showing all the tests executed in the reporter file

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.

Protractor Times Out Waiting For Element

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');
});
});

Categories