Should we write callbacks/promises for the re-usable methods in Page Object Pattern based testing in Protractor?
For example .. I have the below test code and Page Objects and its working fine without issues. But should I add callbacks for re-usable methods in page class?
describe('This is a test suite for Login cases',function(){
beforeEach(function() {
LoginPage.goHome();
LoginPage.doLogin();
});
afterEach(function() {
LoginPage.doLogout();
});
it('Scenario1_Login_VerifyFirstName',function(){
//Some Test step
});
Page Class:
var Login = {
PageElements: {
emailInput: element(by.css('.email')),
passwordInput: element(by.css('.password')),
loginForm: element(by.css('.form')),
logout: element(by.linkText('LOG OUT'))
},
goHome: function goHome() {
browser.get('/signin');
browser.driver.manage().window().maximize();
},
doLogin: function doLogin() {
this.PageElements.emailInput.sendKeys(UserName);
this.PageElements.passwordInput.sendKeys(Password);
this.PageElements.loginForm.submit();
},
doLogout: function doLogout() {
browser.wait(EC.elementToBeClickable(this.PageElements.profileLink));
this.PageElements.profileLink.click();
this.PageElements.logout.click();
}
};
module.exports = Login;
Yes you can.
By simply returning values or promises:
goHome: function() {
browser.get('/home');
return browser.getTitle();
},
And should resolve them on spec level inside "it" blocks like below:
it('Page should have a title', function() {
expect(Page.goHome()).toEqual('Home Page');
});
Related
Hi I am new to javascript and Nightwatch, I am a manual tester who started doing automation about 6 months ago.
I am writing test cases for checking the details of a product, with collapsible menus. Pressing + button will open and display a list of elements, when closing with the same button, it closes the list, and shows a counter with the number of items on the list.
I have a function that is correctly doing this procedure, but I have it written on the test. I would like to use it in the Page where I have all elements and functions related to that page. And I would like to call that function from the test. I have been able to do this, but not with cases with nested functions, because I do not know how to write it.
These are my pages:
loginPage.js;
productPage.js;
productFuntionalityListPage.js;
This is my test:
module.exports = {
'Buy a Product with Bank Account': function (browser) {
const login = browser.page.loginPage();
const productList = browser.page.productPage();
const productFunctionalityList = browser.page.productFuntionalityListPage();
login
.navigate()
.checkLoginPage();
productList
.getAProduct()
//------------------------------------------Features--------------------------------------
//function to click on each button for functionalities and wait for list to appear
function displayFunctionsList(elems) {
elems.value.forEach(function (element) {
browser.elementIdClick(element.ELEMENT)
//wait for list to appear
.waitForElementVisible('.list_of_items')
.pause(2000)
})
}
// click on each function and wait for list to appear
browser.elements('css selector', '.expand_collapse_btn', displayFunctionsList, 5000)
browser.useCss()
// close each function
function closeFunctionsList(elems) {
elems.value.forEach(function (element) {
browser.elementIdClick(element.ELEMENT)
//after click close wait for count to appear
.waitForElementVisible("input[data-id='counter']")
.pause(2000)
})
}
browser.elements('css selector', '.expand_collapse_btn', closeFunctionsList, 2000)
browser.end()
}
}
This is working correctly.
Below it's what I have tried and does not work:
Page:
productFuntionalityListPage.js
module.exports = {
elements: {
counterOfItemsInList: {
locatorStrategy: 'css selector'
selector: "input[data-id='counter']",
},
expandCollapseBtn: {
locateStrategy: 'css selector',
selector: '.expand_collapse_btn',
},
listOfItems: {
locateStrategy: 'css selector',
selector: '.list_of_items',
}
},
commands: [{
displayFunctionsList: function () {
function displayFunctionsList(elems) {
elems.value.forEach(function (element) {
this.elementIdClick(element.ELEMENT)
//wait for list to appear
.waitForElementVisible('#listOfItems')
.pause(2000)
})
}
this.elements('css selector', '#expandCollapseBtn', displayFunctionsList, 5000)
},
closeFunctionsList: function () {
function closeFunctionsList(elems) {
elems.value.forEach(function (element) {
this.elementIdClick(element.ELEMENT)
//wait for list to appear
.waitForElementVisible('#counterOfItemsInList')
.pause(2000)
})
}
this.elements('css selector', '#expandCollapseBtn', closeFunctionsList, 5000)
}
}]
}
Test calling function from page:
module.exports = {
'Buy a Product with Bank Account': function (browser) {
const login = browser.page.loginPage();
const productList = browser.page.productPage();
const productFunctionalityList = browser.page.productFuntionalityListPage();
login
.navigate()
.checkLoginPage();
productList
.getAProduct()
//------------------------------------------Features--------------------------------------
//calling displayFunctionsList from productFuntionalityListPage.js
productFunctionalityList.displayFunctionsList()
//calling closeFunctionsList from productFuntionalityListPage.js
productFunctionalityList.closeFunctionsList()
browser.end()
}
}
Result after running the test above:
Error:
TypeError: this.elements is not a function
- writing an ES6 async test case? - keep in mind that commands return a Promise;
- writing unit tests? - make sure to specify "unit_tests_mode=true" in your config.
Could anyone please help me adding these functions as custom commands in the productFuntionalityListPage.js and call these functions from the test itself? Not sure what's wrong, because of my lack of javascript and nightwatch knowledge.
Try passing browser as a variable when calling the function like this -
##Test page##
//Example call
gmail.selectEmail(browser, 'browser authentication')
And then the method in the pageObject -
##Page Object##
//Example Method
selectEmail(browser, searchValue){
browser.blah(searchValue);
browser.blah
browser.blah
};
Its slightly messy way of getting it to work but this has saved my bacon a few times
(I asked this question recently and accepted an answer but it's still not what I need.) I really need to create dynamic tests from data loaded from a module. Each item from the array will have it's own describe statement with certain protractor actions. My previous post has an answer that says to use an it statement, but I can't do that because there's too much going on.
My main problem is that the data doesn't get loaded in time for the describe. I had another suggestion to use VCR.js or something similar but I don't think those will work because I'm using a module. Is there a way I can save the data to a separate file and load it in? Would that be a good way to go?
var data = require('get-data'); //custom module here
describe('Test', function() {
var itemsArr;
beforeAll(function(done) {
data.get(function(err, result) {
itemsArr = result; //load data from module
done();
});
})
//error: Cannot read property 'forEach' of undefined
describe('check each item', function() {
itemsArr.forEach(function(item) {
checkItem(item);
});
});
function checkItem (item) {
var itemName = item.name;
describe(itemName, function() {
console.log('describe');
it('should work', function() {
console.log('it');
expect(true).toBeTruthy();
});
});
}
});
UPDATE:
I used Eugene's answer and came up with this. I can't test each individual study how I want because the it statement doesn't fire. Is this problem even solvable??
describe('check each item', function () {
it('should load data', function (done) {
browser.wait(itemsPromise, 5000);
itemsPromise.then(function(itemsArr) {
expect(itemsArr).toBeTruthy();
studyArr = itemsArr.filter(function (item) {
return item.enabled && _.contains(item.tags, 'study');
});
studyCount = studyArr.length;
expect(studies.count()).toEqual(studyCount);
checkItems(studyArr);
done();
});
});
function checkItems (itemsArr) {
itemsArr.forEach(function (item) {
describe(item.id, function () {
console.log('checkItems', item.id);
// doesn't work
it('should work', function (done) {
expect(false).toBeTruthy();
done();
});
});
});
}
});
You're trying to do something that Jasmine does not allow: generating tests after the test suite has started. See this comment on an issue of Jasmine:
Jasmine doesn't support adding specs once the suite has started running. Usually, when I've needed to do this, I've been able to know the list of options ahead of time and just loop through them to make the it calls. [...]
("adding specs" === "adding tests")
The point is that you can generate tests dynamically but only before the test suite has started executing tests. One corollary of this is that the test generation cannot be asynchronous.
Your second attempt does not work because it is trying to add tests to a suite that is already running.
Your first attempt is closer to what you need but it does not work either because describe calls its callback immediately, so beforeAll has not run by the time your describe tries to generate the tests.
Solutions
It all boils down to computing the value of itemsArr before the test suite start executing tests.
You could create a .getSync method that would return results synchronously. Your code would then be something like:
var data = require('get-data'); //custom module here
var itemsArr = data.getSync();
describe('Test', function() {
describe('check each item', function() {
itemsArr.forEach(function(item) {
checkItem(item);
});
});
[...]
If writing .getSync function is not possible, you could have an external process be responsible for producing a JSON output that you could then deserialize into itemsArr. You'd execute this external process with one of the ...Sync functions of child_process.
Here's an example of how the 2nd option could work. I've created a get-data.js file with the following code which uses setTimeout to simulate an asynchronous operation:
var Promise = require("bluebird"); // Bluebird is a promise library.
var get = exports.get = function () {
return new Promise(function (resolve, reject) {
var itemsArr = [
{
name: "one",
param: "2"
},
{
name: "two",
param: "2"
}
];
setTimeout(function () {
resolve(itemsArr);
}, 1000);
});
};
// This is what we run when were are running this module as a "script" instead
// of a "module".
function main() {
get().then(function (itemsArr) {
console.log(JSON.stringify(itemsArr));
});
};
// Check whether we are a script or a module...
if (require.main === module) {
main();
}
Then, inside the spec file:
var child_process = require('child_process');
var itemsArr = JSON.parse(child_process.execFileSync(
"/usr/bin/node", ["get-data.js"]));
describe('Test', function() {
itemsArr.forEach(function(item) {
checkItem(item);
});
function checkItem (item) {
var itemName = item.name;
describe(itemName, function() {
console.log('describe');
it('should work', function() {
console.log('it');
expect(true).toBeTruthy();
});
});
}
});
I've tested the code above using jasmine-node. And the following file structure:
.
├── data.js
├── get-data.js
└── test
└── foo.spec.js
./node_modules has bluebird and jasmine-node in it. This is what I get:
$ ./node_modules/.bin/jasmine-node --verbose test
describe
describe
it
it
Test - 5 ms
one - 4 ms
should work - 4 ms
two - 1 ms
should work - 1 ms
Finished in 0.007 seconds
2 tests, 2 assertions, 0 failures, 0 skipped
Try to use a promise, something like:
var deferred = protractor.promise.defer();
var itemsPromise = deferred.promise;
beforeAll(function() {
data.get(function(err, result) {
deferred.fulfill(result);
});
})
And then:
describe('check each item', function() {
itemsPromise.then(function(itemsArr) {
itemsArr.forEach(function(item) {
checkItem(item);
});
});
});
Another solution I can think of is to use browser.wait to wait until itemsArr becomes not empty.
Is your get-data module doing some browser things with protractor? If so, you will need to set/get itemsArr within the context of the controlFlow. Otherwise it will read all the code in the get-data module, but defer its execution and not wait for it to finish before moving right along to those expect statements.
var data = require('get-data'); //custom module here
var itemsArr;
describe('Test', function() {
beforeAll(function() {
// hook into the controlFlow and set the value of the variable
browser.controlFlow().execute(function() {
data.get(function(err, result) {
itemsArr = result; //load data from module
});
});
});
//error: Cannot read property 'forEach' of undefined
describe('check each item', function() {
// hook into the controlFlow and get the value of the variable (at that point in time)
browser.controlFlow().execute(function() {
itemsArr.forEach(function(item) {
checkItem(item);
});
});
});
function checkItem (item) {
var itemName = item.name;
describe(itemName, function() {
console.log('describe');
it('should work', function() {
console.log('it');
expect(true).toBeTruthy();
});
});
}
});
I'm writing a few tests for an Angular application, these are my first stab at unit tests for Angular using Jasmine. I'm having trouble structuring the test to cater for the various scenarios inside the function (namely the if statement and callbacks).
Here's my $scope function, which takes an Object as an argument, and if that object has an id, then it updates the object (as it'll already exist), otherwise it creates a new report and pushes to the backend using the CRUD service.
$scope.saveReport = function (report) {
if (report.id) {
CRUD.update(report, function (data) {
Notify.success($scope, 'Report updated!');
});
} else {
CRUD.create(report, function (data) {
$scope.report = data;
Notify.success($scope, 'Report successfully created!');
});
}
};
My test so far passes in a fake Object with an id so it'll trigger the CRUD.update method, which I then check is called.
describe('$scope.saveReport', function () {
var reports, testReport;
beforeEach(function () {
testReport = {
"id": "123456789",
"name": "test"
};
spyOn(CRUD, 'update');
$scope.saveReport(testReport);
});
it('should call CRUD factory and update', function () {
expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function));
});
});
I understand Jasmine doesn't allow multiple spies, but I want to be able to somehow test for the if condition, and run a mock test for when the Object doesn't pass in an Object too:
describe('$scope.saveReport', function () {
var reports, testReport;
beforeEach(function () {
testReport = {
"id": "123456789",
"name": "test"
};
testReportNoId = {
"name": "test"
};
spyOn(CRUD, 'update');
spyOn(CRUD, 'create'); // TEST FOR CREATE (NoId)
spyOn(Notify, 'success');
$scope.saveReport(testReport);
$scope.saveReport(testReportNoId); // TEST FOR NO ID
});
it('should call CRUD factory and update', function () {
expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function));
// UNSURE ON THIS PART TOO
});
});
I've read things about using the .andCallFake() method, but I could not see how this could work with my setup. Any help really appreciated.
It seems that you should decide on what you need to test first. If you want to test simply that update is called when id exists or create is called when it does not then you should just structure the it function with those conditions. The before each is the wrong place for some of those things.
it('should call CRUD factory and update', function () {
spyOn(CRUD, 'update');
$scope.saveReport(testReport);
expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function));
});
it('should call CRUD create', function() {
spyOn(CRUD, 'create');
$scope.saveReport(testReportNoId); // TEST FOR NO ID
expect(CRUD.create).toHaveBeenCalledWith(testReport, jasmine.any(Function));
});
Only put things in the before each that you actually should do before each test.
Hope this helped!
I would like to run Protractor tests on two separate pages in my Angular app: /dashboard and /articles.
The complication is that I have to log in to the app manually.
Currently I have this setup:
var LoginPage = function() {
ptor = protractor.getInstance();
this.login = function(url) {
ptor.get(url);
ptor.findElement(protractor.By.model('email')).sendKeys(config.LOGIN_EMAIL);
ptor.findElement(protractor.By.model('password')).sendKeys(config.LOGIN_PASS);
ptor.findElement(protractor.By.tagName('button')).click();
};
};
describe('The dashboard', function() {
console.log('logging in');
var loginPage = new LoginPage();
loginPage.login(config.DASHBOARD_URL);
console.log('logged in');
it('has a heading', function() {
console.log('testing dashboard 1');
heading = ptor.findElement(protractor.By.tagName('h1'));
expect(heading.getText()).toEqual(config.DASHBOARD_HEADING);
});
});
describe('The article widget', function() {
console.log('logging in');
var loginPage = new LoginPage();
loginPage.login(config.ARTICLE_URL);
console.log('logged in');
it('has a heading', function() {
console.log('testing article 1');
heading = ptor.findElement(protractor.By.tagName('h1'));
expect(heading.getText()).toEqual(config.ARTICLES_HEADING);
});
});
This gives me the following output:
Selenium standalone server started at http://192.168.2.9:56791/wd/hub
logging in
LoginPage
logged in
logging in
LoginPage
logged in
testing dashboard 1
Ftesting article 1
It looks as though both the describe sections are kicking off in parallel. How can I force the following sequence of events, while still structuring the code in a sensible way?
Load dashboard page
Log in
Run dashboard tests
Load article page (Assume we are already logged in)
Run article tests
You can move the login to another file.
Then, in your protractor configuration file do this:
exports.config = {
specs: [
'spec/login.js',
'spec/dashboard_test.js',
'spec/article_test.js'
],
...
};
Login will run before the other tests
describe('my app', function(){
beforeEach(function(){
login()...
})
describe('dashboard');
describe('the article widget')
});
The Protractor documentation recommends
put your log-in code into an onPrepare function, which will be run once before any of your tests.
For example in your protractor.conf
onPrepare: function() {
browser.driver.get('http://localhost/login.html');
browser.driver.findElement(by.id('username')).sendKeys('Jane');
browser.driver.findElement(by.id('password')).sendKeys('1234');
browser.driver.findElement(by.id('clickme')).click();
// Login takes some time, so wait until it's done.
// For the test app's login, we know it's done when it redirects to
// index.html.
return browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /index/.test(url);
});
}, 10000);
}
I had a similar issue with my e2e protractor tests. Describe blocks were being executed in parallel, causing my tests to fail.
My code before the fix was something like:
describe('test1', function() {
it('do foo1', function() {..});
describe('do test1', function() {..});
});
describe('test2', function() {
it('do foo2', function() {..});
describe('do test2', function() {..});
});
Both the describe blocks were being executed in parallel causing my tests to fail. The fix was to enclose the it blocks in describe blocks.
Code after the fix:
describe('test1', function() {
describe('foo1', function() {
it('do foo1', function() {..});
});
describe('do test1', function() {..});
});
describe('test2', function() {
describe('foo2', function() {
it('do foo2', function() {..});
});
describe('do test2', function() {..});
});
Link to a similar issue on protractor github: https://github.com/angular/protractor/issues/592
I am trying to test a function that requires a module using jasmine and requirejs.
Here is a dummy code:
define("testModule", function() {
return 123;
});
var test = function() {
require(['testModule'], function(testModule) {
return testModule + 1;
});
}
describe("Async requirejs test", function() {
it("should works", function() {
expect(test()).toBe(124);
});
});
It fails, because it is an async method. How can I perform a test with it?
Note: I dont want to change my code, just my tests describe function.
For testing of an asynchronous stuff check runs(), waits() and waitsFor():
https://github.com/pivotal/jasmine/wiki/Asynchronous-specs
Though this way looks a bit ugly as for me, therefore you could also consider following options.
1. I'd recommend you to try jasmine.async that allows you to write asynchronous test cases in this way:
// Run an async expectation
async.it("did stuff", function(done) {
// Simulate async code:
setTimeout(function() {
expect(1).toBe(1);
// All async stuff done, and spec asserted
done();
});
});
2. Also you can run your tests inside require's callback:
require([
'testModule',
'anotherTestModule'
], function(testModule, anotherTestModule) {
describe('My Great Modules', function() {
describe('testModule', function() {
it('should be defined', function() {
expect(testModule).toBeDefined();
});
});
describe('anotherTestModule', function() {
it('should be defined', function() {
expect(anoterTestModule).toBeDefined();
});
});
});
});
3. Another point is I guess that this code is not working as you're expecting:
var test = function() {
require(['testModule'], function(testModule) {
return testModule + 1;
});
};
Because if you call test(), it won't return you testModule + 1.