Protractor page objects error - javascript

I'm building my angularjs protractor e2e test to the page objects pattern. I'm facing trouble with converting my script in to page object.
Here is my conf.js
// conf.js
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['employee.js']
}
Here is my employee.js
// spec.js
var EmpPageObject = require('./EmpPageObject.js');
describe('Protractor Demo App', function() {
it('should have a title', function() {
var empPageObject = new EmpPageObject();
empPageObject.get();
empPageObject.setName('mee');
empPageObject.setPassword('123');
});
});
Here is my EmpPageObject.js
var EmpPageObject = function() {
var nameInput = element(by.model('login.user_name'));
var passwordInput = element(by.model('login.password'));
var addButton = element(by.css('.btn'));
this.get = function() {
browser.get('http://');
};
this.setName = function(name) {
nameInput.sendKeys(name);
};
this.setPassword = function(password) {
passwordInput.sendKeys(password);
};
addButton.click();
};
But, my script fails giving the following error.
Failures:
1) Protractor Demo App should have a title
Message:
Failed: EmpPageObject is not defined
This may be a dumb question. But, I cannot find the error since this is my first test. :)

Look like you copy-paste code from here
https://github.com/angular/protractor/blob/f9c8a37f7dbec1dccec2dde0bd6884ad7ae3f5c7/docs/tutorial.md
describe('Protractor Demo App', function() {
it('should have a title', function() {
browser.get('http://juliemr.github.io/protractor-demo/');
expect(browser.getTitle()).toEqual('Super Calculator');
});
});
Here is protractor try to get resource and check - is it have title.
This function return true or false to make test. In your case, function return undefined, it is equal to false, test fail and you get error message.

Related

Protractor example test fails when running from command line. cannot read property '$$testability' of unefined

Config file
this is my conf.js file
// An example configuration file.
exports.config = {
directConnect: true,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directory when
// protractor is called.
specs: ['example_spec.js'],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
Example Spec.js
is there anything wrong with the code here should i add some type of wait time
describe('angularjs homepage', function() {
it('should greet the named user', function() {
browser.get('http://www.angularjs.org');
element(by.model('yourName')).sendKeys('Julie');
var greeting = element(by.binding('yourName'));
expect(greeting.getText()).toEqual('Hello Julie!');
});
describe('todo list', function() {
var todoList;
beforeEach(function() {
browser.get('http://www.angularjs.org');
todoList = element.all(by.repeater('todo in todoList.todos'));
});
it('should list todos', function() {
expect(todoList.count()).toEqual(2);
expect(todoList.get(1).getText()).toEqual('build an AngularJS app');
});
it('should add a todo', function() {
var addTodo = element(by.model('todoList.todoText'));
var addButton = element(by.css('[value="add"]'));
addTodo.sendKeys('write a protractor test');
addButton.click();
expect(todoList.count()).toEqual(3);
expect(todoList.get(2).getText()).toEqual('write a protractor test');
});
});
});
Error Code
this is the error I am getting
This seems to be a common issue with protractor if any one can assist me with a fix to get this test running please do
Thanks
Mike,

protractor, on login form sendkeys() are not working. Browser don't displays my value for the form fields

(I'm not using jQuery) Hi! I'm starting with protractor and cucumber and i'm testing a login page.
I'm trying to insert values on a form for the login, but when i lunch the configuration file to lunch the test, Chrome open the login page but don't displays the values that i setted for the required fields.
Clicking on sumbit button, the page should be redirect to another. Can anyone help me? How i have to change my step definition file to make it works? Thank you
I think that there are some problems like in configuration and others.
Here is step definition:
This is my new step definition file:
Given("I'm on site login page", function () {
//return pending;
browser.driver.get('https://www.websiteurl.com/login.html');
browser.sleep(20000);
});
When('I see the submit-button', function () {
// Write code here that turns the phrase above into concrete actions
//var sumbit = browser.executeScript('document.getElementById("submit-//wrap.cf.input-formFields")');
var sumbit = element(by.css('.submit-wrap.cf.input-formFields'));
expect(sumbit).to.not.be.null;
});
When('I filled all the mandatory fields', function () {
// Write code here that turns the phrase above into concrete actions
window.onload = function(){
var bookingNumberField = browser.executeScript('document.getElementById("variation2-bookingNumber").getText()');
var firstNameField = browser.executeScript('document.getElementById("variation2-firstName").getText()');
var lastNameField = browser.executeScript('document.getElementById("variation2-lastNameField").getText()');
var dobMonth = browser.executeScript('document.getElementById("month").getText()');
var dobDay = browser.executeScript('document.getElementById("day").getText()');
var dobYear = browser.executeScript('document.getElementById("year").getText()');
// var firstNameField = document.getElementById("variation2-firstName");
// var lastNameField = document.getElementById("variation2-lastName");
// var dobMonth = document.getElementById("month");
// var dobDay = document.getElementById("day");
// var dobYear = document.getElementById("year");
browser.sleep(1000);
//browser.waitForAngular();
//browser.executeScript to cut eventually
browser.executeScript.bookingNumberField.clear().sendKeys('WJXMHH');
browser.executeScript.firstNameField.clear().sendKeys('Mark');
browser.executeScript.lastNameField.clear().sendKeys('Altria');
element(by.cssContainingText('option', 'March')).click();
element(by.cssContainingText('option', '10')).click();
element(by.cssContainingText('option', '1991')).click();
TermsChkbxLabel = element(by.css("label[for='checkboxb']"));
TermsChkbxLabel.click();
}
}); //loginBtn.click();
Then('I am able to click on it to login', function () {
// var ptor = protractor.getInstance();
// ptor.ignoreSynchronization = true;
// var login_b = browser.executeScript('document.getElementById("login-button").click()');
//var login_b = document.getElementsByClassName("login-button").click();
// ptor.sleep(10000);
// var expectedUrl = ptor.getCurrentUrl();
// //expect(expectedUrl).toEqual('https://www.websiteurl.com/newpage.html');
});
Then('I am able to open the new page', function () {
var login_b = element(by.css('.login-button'));
login_b.click();
// var ptor = protractor.getInstance();
// ptor.ignoreSynchronization = true;
// var login_b = document.getElementsByClassName("login-button").click();
// ptor.sleep(10000);
// var expectedUrl = ptor.getCurrentUrl();
//
});
Here is the protractor conf.js:
var seleniumServer = require('selenium-server')
var nightwatchCucumber = require('nightwatch-cucumber')
require('babel-core/register');
var nightwatchCucumberConf = {
runner: 'nightwatch',
featureFiles: 'features',
stepDefinitions: 'features/step_definitions/testing_1_6.js',
closeSession: 'afterFeature'
};
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'),
plugins: [{
path: require.resolve('protractor-console'),
logLevels: ['severe']
}],
directConnect: true, //chrome only
jasmineNodeOpts: {},
onPrepare: function() {},
capabilities: {
'browserName': 'chrome'
},
// Spec patterns are relative to this directory.
specs: [
'features/*.feature'
],
baseURL: 'https://www.websiteurl.com/login.html',
cucumberOpts: {
//require: 'features/step_definitions/**/*.js',
require: 'features/step_definitions/testing_1_6.js',
tags: false,
// format: 'pretty',
profile: false,
'no-source': true
}
};
I have this error too:
[12:57:27] E/launcher - Error while waiting for Protractor to sync with the page: "both angularJS testability and angular testability are undefined. This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping. See http://git.io/v4gXM for details"
[12:57:27] E/launcher - Error: Error while waiting for Protractor to sync with the page: "both angularJS testability and angular testability are undefined. This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping.
Step definition file testing_1_6.js:
// chai is an assertion library
var chai = require('chai');
// chai-as-promised is an helper to handle promise
var chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised);
expect = chai.expect;
Given("I'm on site login page", function() {
browser.driver.get('https://www.websiteurl.com/login.html');
return browser.sleep(20000);
});
When('I see the submit-button', function() {
var sumbitBtn = element(by.css('.submit-wrap.cf.input-formFields'));
return expect(sumbitBtn.isDisplayed()).to.eventually.be.true;
});
When('I filled all the mandatory fields', function() {
element(by.id('variation2-bookingNumber')).sendKeys('WJXMHH');
element(by.id('variation2-firstName')).sendKeys('Mark');
element(by.id('variation2-lastNameField')).sendKeys('Altria')
element(by.cssContainingText('#month > option', 'March')).click();
element(by.cssContainingText('#day > option', '10')).click();
element(by.cssContainingText('#year > option', '1991')).click();
return element(by.css("label[for='checkboxb']")).click();
});
Then('I am able to click on it to login', function() {
return element(by.id('login-button')).click();
});
Then('I am able to open the new page', function() {
var newPageUrl = 'https://www.websiteurl.com/newpage.html';
browser.sleep(10000);
return expect(browser.getCurrentUrl()).to.eventually.equal(newPageUrl);
});
protractor conf.js:
exports.config = {
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
getPageTimeout: 60000,
allScriptsTimeout: 500000,
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
plugins: [{
path: require.resolve('protractor-console'),
logLevels: ['severe']
}],
directConnect: true, //chrome only
onPrepare: function() {
browser.ignoreSynchronization = true;
},
capabilities: {
browserName: 'chrome'
},
specs: [
'features/*.feature'
],
cucumberOpts: {
require: [
'features/step_definitions/testing_1_6.js'
]
}
};
browser.waitForAngularEnabled(false);

One specific stub in sinon tests not working

I have a problem and can't seem to find the solution.
I'm writing Node.js code and using Sinon to unittest. I am testing a service and stubbing calls to the repository/database. Everything works despite for one repository method where the actual method is invoked instead of its stub. Here's the relevant code.
listingServiceTest.js
var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var listingService = require('../listingService');
var listingRepository = require('../../repository/listingRepository');
var Listing = require('../../models/interfaceModel/listing');
//some testdata initialization
[..]
describe('saveListing(listing)', function() {
//everything works fine in here
[...]
});
describe('saveTags(listingID, tags)', function() {
beforeEach(function() {
sinon.stub(listingRepository, 'findTags', function(tags, callback) {
//This one works fine
var tags = [{
text: tags[0],
tagID: tags[0] + 'ID'
}];
setTimeout(function () {
callback (tags);
}, 10);
});
sinon.stub(listingRepository, 'saveTagCorrelation', function(listingID, tagID, done) {
setTimeout(function() {
//Here The actual Method is called instead of the stub ?!?!?
console.log('im saveTagCorrelation stub');
done();
}, 10);
});
sinon.stub(listingRepository, 'saveTag', function(tag, callback) {
//This one works fine
});
});
afterEach(function() {
listingRepository.findTags.restore();
listingRepository.saveTag.restore();
listingRepository.saveTagCorrelation.restore();
});
it("saveTags should execute this callback", function() {
listingService.saveTags(util.slugify(pTitle), pTags, function() {
//This obviously fails since the the stub isn't called
expect(listingRepository.saveTagCorrelation.getCall(0).args[0]).to.equal(util.slugify(pTitle));
expect(listingRepository.saveTagCorrelation.getCall(0).args[1]).to.equal(pTags[0] + 'ID');
expect(listingRepository.saveTag.getCall(0).args[0]).to.equal(pTags[1]);
expect(listingRepository.saveTagCorrelation.getCall(1).args[0]).to.equal(util.slugify(pTitle));
expect(listingRepository.saveTagCorrelation.getCall(1).args[1]).to.equal(pTags[1] + 'ID');
});
});
});
And here's the repo, that is supposed to be stubbed (I can see in the logs, that the actual method is logging, instead of the stub).
listingRepository.js:
var db = require ('../models/index');
var util = require ('../util');
module.exports = {
saveListing: [...],
findTags: [...],
saveTag: [...],
saveTagCorrelation: function (listingID, tagID){
//This is called instead of the stub
console.log('in actual Method');
var tagToSave;
tagToSave = db.tag_listing.build({
listingID: listingID,
tagID: tagID
});
tagToSave.save();
},
getListingByID: [...]
}
Am I blind? What am I missing?

Why is the driver object defined, but the webdriver object is not?

Question
Why does driver work fine(the title is retrieved and tested), but web driver is undefined(unable to getText)?
Expected Result
The tests will complete successfully.
Actual Result
․ Google when at home Page should have correct title: 141ms
1) Google when at home Page when searching should input search term
1 passing (3s)
1 failing
1) Google when at home Page when searching should input search term:
ReferenceError: webdriver is not defined
Files Used
Test File
Used to run the tests by executing command: mocha -t -R list index.js (assuming index.js is the filename)
var fs = require('fs'),
chai = require('chai'),
assert = chai.assert,
expect = chai.expect,
test = require('selenium-webdriver/testing'),
webdriver = require('selenium-webdriver'),
Page = require('./pageobjects/pages/home');
test.describe('Google', function(){
test.before(function(){
driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.firefox()).
build();
//initialize driver and webdriver on the Page Object
Page.webdriver = webdriver;
Page.driver = driver;
});
test.describe("", function () {
test.before(function(){
//console.log(Page);
});
test.describe("when at home Page", function () {
test.before(function () {
Page.get(Page.URL);
});
test.it("should have correct title", function () {
Page.getTitle()
.then(function (title) {
assert.equal(title, 'Google');
});
});
test.describe("when searching", function () {
test.it("input search term", function () {
Page.sendKeys(Page.Search.INPUT, 'test');
Page.getText(Page.Search.INPUT)
.then(function (text) {
assert.equal(text, 'test');
});
});
});
test.after(function () {
driver.quit();
});
});
});
});
Page
object used to create pages
var Page = {
getTitle : function getTitle() {
return driver.getTitle();
},
get : function get(url) {
return driver.get(url);
},
sendKeys : function sendKeys(element, text) {
console.log(webdriver);
driver.findElement(webdriver.By.css(element)).sendKeys(text);
},
click : function click(element) {
return driver.findElement(webdriver.By.css(element)).click();
}
};
module.exports = Page;
Home
object that represents a page, uses mixins to get Page's functions
the search file is left out because it is irrelevant to the problem
var Page = require('./page'),
Search = require('../components/search'),
extend = require('extend');
var Home = {
URL : 'http://google.com',
Search : Search
};
module.exports = Home;
//extend home with page
extend(module.exports, Page);

How can I set up common functions that are available for my test suites with Protractor / Selenium?

I am working on an AngularJS protractor test suite. I have a conf file looking like this:
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
baseUrl: 'http://127.0.0.1:17315/',
capabilities: {
browserName: 'chrome',
'chromeOptions': {
args: ['--test-type']
}
},
suites: {
login: ['LoginPage/login.js'],
homePage: ['Homepage/homepage.js',
'Homepage/city_page.js',
'Homepage/admin_page.js'],
adminPage: ['AdminPage/exam.js',
'AdminPage/location.js'
..
Inside these .js files I use some functions that I would like to
share amongst all of my files. For example:
describe('xxx', function () {
it('xxx', function () {
commonFunction(123);
});
I would like to place these common functions in their own file but I am not sure how to do this so that I can make them accessible from the other javascript files. I guess what I need is something like an "inport" which I don't think exists.
Can anyone give me some advice on where I can put these common functions and on how I can access them from each of the *.js files in the test suites?
To reuse code i use the page object pattern. I put the page object in a separate file and in a module.
For example, the pages.js file contains some page objects.
'use strict';
(function() {
var Application = function() {
var app = this;
browser.get('http://localhost:9003/');
app.login = function() {
element(by.buttonText('login')).click();
return new LoginPage();
};
var LoginPage = function() {
var loginPage = this;
loginPage.withCredentials = function(login, password) {
element(by.css('.loginField')).Keys(login);
element(by.css('.passwordField')).Keys(password);
element(by.buttonText('login')).click();
return new WelcomePage();
};
};
var WelcomePage = function() {
var welcomePage = this;
welcomePage.getGreetings = function() {
return element(by.css('.greetings')).getText();
};
};
};
module.exports = function() {
return new Application();
};
}());
and i import them in my acceptance test using require:
'use strict';
var Application = require('./pages.js');
describe('The application', function() {
it('should let you log into the application', function() {
var application = new Application();
var welcomePage = application.login().withCredentials('Jean', '!sz3sk,dz');
expect(welcomePage.getGreetings()).toEqual('Welcome Jean');
});
});

Categories

Resources