How to identify element for notifications that disappear within few seconds? - selenium

I've a test case where after creation of an item, notification is shown, but that notification disappear s within 2-3 seconds.
I want to identify the element for that notification, but when I try to inspect element for that in firebug, it's HTML snippet disappears very quickly since notification itself disappears. Hence I couldn't identify element for it and finding it very difficult to automate.
Can anyone suggest how to deal with such situation?

Since you say "I've a test case", I'm thinking you are testing an application of yours. The plainest way to get around your problem is to know your application. Even if a third-party library is providing the notification code, you can read the doc to see if you can increase the delay or you can read the source code to figure out how it creates the element and where.
If the above fails, then if you can get together a sequence of operations in Selenium that triggers a notification, you should be able to get a serialization of body quickly enough that you can then examine at your leisure. Using Selenium for Python, it would go:
print driver.execute_script("return document.body.outerHTML;")
I would run the code above with redirection to save the output of the print statement to a file that I'd then examine at my leisure. You could make it narrower if you wish by getting the outerHTML of a descendant of body. I like to have a good bit of context so that I know where exactly the element is being created. I've used libraries and configurations that create such notifications as children of body, and some that put them as children of other elements.

Open the previous page before the notification
Press "Ctrl+Shift+c", Navigate to "sources" tab
Do the manual step to generate the notification, which is going to hide in few seconds
Press "F8". Page load scripts will be paused
Then inspect the element as usual and fetch the xpath at your convenience

You can use the below JAVA code to wait for 20 seconds till any element with text 'your notification' appears in the page:
try{
WebDriverWait wait = new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'Your notification here')]")));
}catch(Throwable e){
System.err.println("Error while waiting for the notification to appear: "+ e.getMessage());
}

Related

How to indicate certain events to Selenium tests?

I'm relatively new to Selenium testing. I have a React SPA I want to create Selenium tests for. I can work with locators and such, but I don't know how I can make the test wait for certain events.
I.e.: The test opens a page where I have a list that is loaded via an API. I need the test to wait until the content is loaded. How can I indicate this to the test? I may be able to check the spinner and wait until it disappears, but there could be situations when the spinner doesn't even appear. Besides, I need to handle events when there are no elements in the list or when there is a communication issue with the API. I really don't want to rely on user messages and spinners.
Should I create an DOM element which is invisible to the user and fill it with the event result so the test can read it? This also doesn't seem a good solution for me.

Selenium - when exactly the webdriver instance gets updated?

I'm using selenium to automate a task on a very dynamic website with pyhton.
For this reason certain HTML elements of the current loaded page may or may not be present at the moment of the request from my code.
How exactly the webdriver instance gets updated and receives the new data from the web page?
Is it constantly connected and receive the change in the HTML code instantly?
Or it first download a first verion of the page when driver.get() is called, and then updates it whenever a function such as .find_element_by_class_name() is called?
Q. Is it constantly connected and receives the change in the HTML code instantly?
Ans. Well, for each Selenium command, there will be an HTTP request that will send to the browser driver and then to the server and the command will get, A HTTP response will be returned and the command/commands will get executed based on the response.
Now let's say in a situation you do,
driver.get()
Basically, this is a selenium command.
It would fire an HTTP request stating to launch the URL provided. Based on the response (200-Ok or anything else), you would either see the WebPage getting loaded or an error message.
Same way in Sequence all the Selenium commands will get executed.
It's obvious that we need locators to locate web elements in the UI.
Once we have them, we can tightly couple them with
driver.find_element_by_***
methods.
Things to be noted down here
You need to learn/understand :
Implicit Waits.
Explicit Waits.
Fluent Waits.
Implicit Waits :
By implicitly waiting, WebDriver polls the DOM for a certain duration when trying to find any element. This can be useful when certain elements on the webpage are not available immediately and need some time to load.
Basically what it means is, whenever you use drive.find_element it gonna look for implicit waits if you have defined one.
If you've not defined one implicit wait, then the default value is 0.
Explicit wait
They allow your code to halt program execution, or freeze the thread, until the condition you pass it resolves. The condition is called with a certain frequency until the timeout of the wait is elapsed. This means that for as long as the condition returns a falsy value, it will keep trying and waiting.
FluentWait
FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.
Reference Link
Updated :
PS : Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.
Steps to check:
Press F12 in Chrome -> go to element section -> do a CTRL + F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.
Locators (by priority from top):
ID
name
classname
linkText
partialLinkText
tagName
css selector
xpath
Web page is loaded by driver.get().
But the driver doesn't "know" what elements are existing there. It just opens, loads the web page.
To access any element, to check element presence etc. you will need to do that particularly per each specific element / elements using commands like .find_element_by_class_name() with a specific element locator.

Capture HTML after element has been changed

I am looking for automated way to capture HTML after I do some actions on the web page.
For example I select some item in dropdown and HTML has been changed, i want to capture that HTML and dump into file. As result, I will end up with many different HTML files on my hdd.
I was thinking it might be possible to achieve that by using Selenium, maybe some other plugin which would give me possibility so save HTML in automatic manner to file.
do you mean source code?
for Python:
driver.page_source
for Java:
driver.getPageSource();
you can run these code after each step where page is changed
I think what you are asking to do will not be that easy. There are other questions on SO (e.g. this one) asking the same thing and there aren't really any good answers. I tried googling for a few mins to find a way to do this. I would think something more like a browser plug-in would exist that would do this for you.
If I were forced to code this using Selenium I would do something like the following...
Create a script that launches the browser and navigates to the page you want to track. In a user-defined interval, the script would grab the page source and compare it to the last capture. If the source is not the same, it would diff the two pages and write the diff to disk. I'm sure there are a number of diffing libraries you could find and use.
The problems with this approach...
If you made too many changes within the defined interval, you would get a glob of changes and not be able to differentiate what action made what change.
If you make the interval too small, you may run into perf issues.
Probably the most significant issue is going to be the fact that you run several tests and then go back and look at the diffs... but you won't have any way to tell what changes correspond to what action since you can't tie the two together other than order of occurrence.
What might be cool is if you could inject a button into the page that when clicked would popup an input dialog that you could type some text into and use that as a label for the upcoming action diff. For example, you click the button and type "choose price" - OK. Now you select a price from a dropdown. The next time you click the button, the script detects the button click and does a quick diff and writes it to disk using the "choose price" label... or something like that.
I found answer for my own question.
Start a selenium chrome driver server.
Use selenium client connect to and all changes could be captured by using code example below:
Code:
WebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:9515"), DesiredCapabilities.chrome());
driver.get("http://google.com");
By by = new By.ByTagName("div");
List<WebElement> oldDivs = driver.findElements(by);
while(true){
try {
List<WebElement> newDivs = driver.findElements(by);
if (oldDivs != newDivs) {
for (WebElement element : newDivs) {
String a = element.getAttribute("a");
String b = element.getAttribute("b");
System.out.println(a + " :" + b);
}
}
}catch (Exception e){
System.err.println(e);
}
}

Does selenium / webdriver with protractor wait for async activity in a describe block before continuing?

I have code in a desribe block but some of my set up code is outside of the block. That's the code that sets up elements.
When my code executes it runs fine but then I see the browser go to another page before parts of my test have completed. With a different page on the browser then it looks for elements and throws an exception when they are not there.
So how can I handle this problem of the browser going to another page before tests are completed?
As per my understanding of the question you want to be on the same page and don't want to move to the new page which loads when you click on to a link/button. If this is the case then to be on the same page you cane use.
Use this command -String oldwindow=window.getWindowHandle();
window.switchTo().window(oldwindow);
Use this command just below the button code which throws a new window. I am a java programer thats why the code written is in java.
getWindowHandle Methods stores the url of current window in oldwindow string and by using window.switchTo().window(oldwindow) it won't move to new window because you are passing oldwindow as argument for the command.
For more go through the Webdriver documentation by clicking this link

Where can I read how to make web notifiers such as the StackExchange at the top left side of StackOverflow screen?

I'm not even sure what the name of that is to be able to make a search... but I would like to make those kind of things. Facebook has that too with the messages, notifications and friends requests. Thanks
I'm not sure if you expect anyone to give you a complete tutorial with source code included? :) You should probably do some digging around yourself, since a concrete answer on this could mean to write a few pages :)
How can you dig around?
Thé tool for a job like that is Firebug (IMO).
With bigger tasks like these it makes sense to try to split it up in smaller pieces.
Let's say you go for a widget like the user profile popup on SO.
you need some HTML to display in a popup: right click on any html element on the popup and click the 'inspect element' menu item. This brings you to the HTML tab in firebug. This allows you to figure out how the HTML is structured
you need some CSS to style that popup: when you're browsing the html structure, you might already have noticed that on the right side of it is the CSS that is applied to the active element
you might want to use some animation effects: for that you could use jquery. Have a look here to find out more on which effects are available and how they can be triggered. Fading is used in the profile popup on SO.
then you might ask yourself the question where SO get's that html structure from, right? To find out more about which server calls are made you can use the 'NET' tab in Firebug. (When you hover over your user name (only the first time?), then you should notice there's a call made to something like: http://stackoverflow.com/users/profile-link-stats?_=someLongNumberHere
In firebug you can then inspect the request and response. You should notice that the response is some HTML structure. This HTML structure is then inserted into the DOM.
Sooooo you can kinda glue it all together now:
the user hovers over his user name
the hovering triggers a server call (see step 4): use jquery hover to attach a handler to the user link. (subsequent hovers don't trigger that server call, so there needs to be a check to see if that profile popup was already loaded or not)
when the server call successfully returns (see jquery get), the returned html is inserted into the DOM and a fadeIn effect is triggered.
it seems a mouseout is used to fadeOut the popup
I HOPE this is the answer you were looking for. It took me a while ;)
You probably need to check out stackapps