Whenever I try to run an automated test script written using JavaScript with Protractor, I can see that these two are actually ran in parallel independently of each other. Example:
it("Validation of ND account", function() {
// I logged in, and navigated to the page I need
// And this is where is gets intresting
console.log("\n");
console.log("Before getting number of users");
var numberOfUsers = element(by.xpath('//div[#viewid="userList"]//div[#class="results-count ng-binding"]')).getText().then(function(text) {
console.log(text);
});
console.log("After getting number of users");
// for (i=1, i<numberOfUsers, i++) {
// console.log(i);
// }
});
I assume that I get my logs in the same order - before, number and after, but first I get JS, and then Protractor (because it takes longer to load). This is a result of running this script in console output:
Started
Before getting number of users
After getting number of users
161
With that said, my problem is that if I want to open a page, get an element text and then perform some operations with it(run a FOR loop which is commented out), it won't let do this because it will return an unresolved promise before it even load the page. More precisely what it does is starts opening a page, right away before the page is loaded, it will run that loop, which depends on element from the page. The loop fails because the element isn't appeared yet, and the program still doesn't have its text attribute. So here is the question: is it possible to strictly adhere to the script sequence (to not let JS run scripts written after protractor commands before execution of protractor commands are completed) without JS timeouts or wait functions?
You need to understand Promises and work with the callbacks to make it work sequentially.
For this particular case, you can't wait for numberOfUsers for your test to keep going, you'll have to continue inside the callback function:
console.log("\n");
console.log("Before getting number of users");
element(by.xpath('//div[#viewid="userList"]//div[#class="results-count ng-binding"]')).getText().then(function(text) {
console.log(text);
// continue working here with "text"
console.log("After getting number of users");
});
Related
(async function() {
try {
let notAvailible = true;
while (notAvailible) notAvailible = await checkAvailible();
if (!notAvailible) orderProduct();
} catch (err) {
console.error(err);
}
})();
will the while loop run until condition notAvailible is false, then run function orderProduct()? or will something unwanted happen?
While this code may work, a few issues:
You have a problematic race condition. Let's say X is available as of the checkAvailable check, but before this code can go to orderProduct, X is no longer available because some other client ordered the available one. Then, orderProduct will fail. You appear to want to loop until the product is available.
The code waits forever for a product to be available. What if that never happens? A timeout would be a good idea.
The code relentlessly hammers the other end, constantly asking "is it available?" "is it available?" "is it available?" (like a toddler asking "Are we there yet?" :-) ). It should at minimum wait a bit, usually backing off in ever-larger steps before (again) giving up at some point.
Instead, have orderProduct send the order to the server (or database or whatever), and have that part of the system atomically order the product — and if that fails, say whether it failed because the product is not available or for some other reason, so that this code knows whether to retry. If the result from the server is "not available," wait a bit (with the incrementally-larger backing off logic) before trying again to place the order; and add a timeout.
tl;dr: When I run my test case, steps executed seem to work, but the test bails out early on a failure to find an element that hasn't even loaded yet. It seems like the waits I have around locating certain elements are loaded/launched as soon as the test is launched, not when the lines should actually be executed in the test case. I think this is happening because the page is barely (correctly) loaded before the "search" for the element to verify the page has loaded bails out. How do I wrangle the event loop?
This is probably a promise question, which is fine, but I don't understand what's going on. How do I implement my below code to work as expected? I'm working on creating automated E2E test cases using Jasmine2 and Protractor 5.3.0 in an Angular2 web app.
describe('hardware sets', () => {
it('TC3780:My_Test', async function() {
const testLogger = new CustomLogger('TC3780');
const PROJECT_ID = '65';
// Test Setup
browser.waitForAngularEnabled(false); // due to nature of angular project, the app never leaves zones, leaving a macrotask constantly running, thus protractor's niceness with angular is not working on our web app
// Navigate via URL to planviewer page for PROJECT_ID
await planListingPage.navigateTo(PROJECT_ID); // go to listing page for particular project
await planListingPage.clickIntoFirstRowPlans(); // go to first plan on listing page
await planViewerPage.clickOnSetItem('100'); // click on item id 100 in the plan
});
});
planViewerPage.po.ts function:
clickOnSetItem(id: string) {
element(by.id(id)).click();
browser.wait(until.visibilityOf(element(by.css('app-side-bar .card .info-content'))), 30000); // verify element I want to verify is present and visible
return expect(element(by.css('app-side-bar .card .info-content')).getText).toEqual(id); //Verify values match, This line specifically is failing.
}
This is the test case so far. I need more verification, but it is mostly done. I switched to using async function and awaits instead of the typical (done) and '.then(()=>{' statement chaining because I prefer not having to do a bunch of nesting to get things to execute in the right order. I come from a java background, so this insanity of having to force things to run in the order you write them is a bit much for me sometimes. I've been pointed to information like Mozilla's on event loop, but this line just confuses me more:
whenever a function runs, it cannot be pre-empted and will run entirely before any other code
runs (and can modify data the function manipulates).
Thus, why does it seem like test case is pre-evaluated and the timer's set off before any of the pages have been clicked on/loaded? I've implemented the solution here: tell Protractor to wait for the page before executing expect pretty much verbatim and it still doesn't wait.
Bonus question: Is there a way to output the event-loop's expected event execution and timestamps? Maybe then I could understand what it's doing.
The behavior
The code in your function is running asynchronously
clickOnSetItem(id: string) {
element(by.id(id)).click().then(function(){
return browser.wait(until.visibilityOf(element(by.css('app-side-bar .card .info-content'))), 30000);
}).then(function(){
expect(element(by.css('app-side-bar .card .info-content')).getText).toEqual(id);
}).catch(function(err){
console.log('Error: ' + err);
})
}
I am looking for a solution, if it is possible to wait for the data entered by the user in protractor.
I mean test stop for a while and I can enter some value and then these data are used in further tests.
I tried to use javascript prompt, but I did not do much, maybe it is possible to enter data in OS terminal?
Please give me an example if it is possible.
I would not recommend mixing the automatic and manual selenium browser control.
That said, you can use Explicit Waits to wait for certain things to happen on a page, e.g. you can wait for the text to be present in a text input, or an element to become visible, or a page title to be equal to something you expect, there are different ExpectedConditions built-in to protractor and you can easily write your own custom Expected Conditions to wait for. You would have to set a reasonable timeout though.
Alternatively, you can pass the user-defined parameters through browser.params, see:
How can I use command line arguments in Angularjs Protractor?
Example:
protractor my.conf.js --params.login.user=abc --params.login.password=123
Then, you can access the values in your test through browser.params:
var login = element(by.id("login"));
login.sendKeys(browser.params.login.user);
If your data will reside in the console, you can get that data by using the following:
browser.manage().logs().get('browser').then(function(browserLogs) {
// browserLogs is an array which can be filtered by message level
browserLogs.forEach(function(log){
if (log.level.value < 900) { // non-error messages
console.log(log.message);
}
});
});
Then as mentioned in other posts, you can explicitly wait for a condition to be true by using driver.wait():
var started = startTestServer();
driver.wait(started, 5 * 1000,
'Server should start within 5 seconds');
driver.get(getServerUrl());
Or expected conditions if waiting for more than one condition, for example.
I had the same question. After a long search I found a solution with Protractor 5.3.2 that worked:
var EC = protractor.ExpectedConditions;
it('will pause for input...', function() {
browser.ignoreSynchronization = true
browser.waitForAngularEnabled(false);
// open web page that contains an input (in my case it was captchaInput)
browser.driver.get('https://example.com/mywebpagehere');
// waits for 15 sec for the user to enter something. The user shall not click submit
browser.wait(EC.textToBePresentInElementValue(captchaInput, '999'), 15000, "Oops :^(")
.then(function() {
console.log('Hmm... Not supposed to run!');
}, function() {
console.log('Expected timeout, not an issue');
});
browser.sleep(1000);
// submit the user input and execution proceeds (in my case, captchaButton)
captchaButton.click();
// . . .
});
I am doing test-driven development with Qunit: when creating a new function, I write tests for it, create the function, reload the page, and if all the tests pass I move on... Whilst this works fine at the beginning, it starts to become a time consuming process after a while as all the tests take several seconds to run, and that's the time I have to wait for every time I refresh my browser.
In an attempt to workaround that problem, I thought about introducing Zombie.js to perform head-less testing: the idea is to have Zombie.js continuously check the webpage (e.g. $ watch -n1 "node queryTheWebpage.js") and report to me Qunits's results while coding (once in a while, as Zombie.js isn't a "real" browser, I would open up a browser and check the page manually to validate).
So far here is what I have for my node/Zombie piece of code:
browser.visit("http://localhost/mywebpage.html", function () {
var qunit_tests = browser.query('body');
console.log(qunit_tests.innerHTML);
});
In the console output I do see the Qunit tests container <ol id="qunit-tests"></ol> but it is empty which means when the visit callback function is called, the tests haven't run.
I've tried to use the wait function to wait for the tests to run, but unsuccessfully:
function waitForQunitToEnd(window) {
var last = window.document.querySelector('selectorOfMyLastTest');
var first_failed = window.document.querySelector('li.failed');
return (last || first_failed);
}
browser.visit("http://localhost/mywebpage.html", function () {
browser.wait(waitForQunitToEnd, function() {
var qunit_tests = browser.query('body');
console.log(qunit_tests.innerHTML); // still gives me empty <ol id="qunit-tests"></ol>
});
});
I tried to play with the waitFor option (e.g. set to 5000ms) but that didn't help either.
Q1: Is what I'm trying to do making sense, or is there a much simpler way of doing something similar?
Q2: Do you know how I could get Zombie.js to wait for the Qunit tests to run?
I don't know if it will help you but look this : http://api.qunitjs.com/QUnit.done/
I am porting an old game from C to Javascript. I have run into an issue with display code where I would like to have the main game code call display methods without having to worry about how those status messages are displayed.
In the original code, if the message is too long, the program just waits for the player to toggle through the messages with the spacebar and then continues. This doesn't work in javascript, because while I wait for an event, all of the other program code continues. I had thought to use a callback so that further code can execute when the player hits the designated key, but I can't see how that will be viable with a lot of calls to display.update(msg) scattered throughout the code.
Can I architect things differently so the event-based, asynchronous model works, or is there some other solution that would allow me to implement a more traditional event loop?
Am I making sense?
Example:
// this is what the original code does, but obviously doesn't work in Javascript
display = {
update : function(msg) {
// if msg is too long
// wait for user input
// ok, we've got input, continue
}
};
// this is more javascript-y...
display = {
update : function(msg, when_finished) {
// show part of the message
$(document).addEvent('keydown', function(e) {
// display the rest of the message
when_finished();
});
}
};
// but makes for amazingly nasty game code
do_something(param, function() {
// in case do_something calls display I have to
// provide a callback for everything afterwards
// this happens next, but what if do_the_next_thing needs to call display?
// I have to wait again
do_the_next_thing(param, function() {
// now I have to do this again, ad infinitum
}
}
The short answer is "no."
The longer answer is that, with "web workers" (part of HTML5), you may be able to do it, because it allows you to put the game logic on a separate thread, and use messaging to push keys from the user input into the game thread. However, you'd then need to use messaging the other way, too, to be able to actually display the output, which probably won't perform all that well.
Have a flag that you are waiting for user input.
var isWaiting = false;
and then check the value of that flag in do_something (obviously set it where necessary as well :) ).
if (isWaiting) return;
You might want to implement this higher up the call stack (what calls do_something()?), but this is the approach you need.