Selenium: are there events like "New element inserted in DOM" - selenium

The site I am testing has a notification logic that brings up a message at the bottom of the screen, keeps it there for one second and then sends it away. When the notification is displayed it hides other elements and that makes my test unstable. I did my best to figure out when the notification is displayed (when the business logic displays it) and dismiss it but every now and then I detect new cases my code are not aware of when the notification is displayed.
Is there a way (using Selenium) to subscribe to an event like "New element inserted in DOM". Dismissing the notification on its callback would solve my problem once and for all.

Selenium doesn't support this use case out of the box but you can achieve that using MutationObserver in javascript. I don't know what language you are using to write selenium test but in C# you can create extensions method as follow
public static void StartWatchingForContentChange(this RemoteWebDriver driver, string containerId, int timeout = SearchElementDefaultTimeout)
{
driver.ExecuteScript(#"var $$expectedId = arguments[0];
__selenium_observers__ = window.__selenium_observers__ || {};
(function(){
var target = document.getElementById($$expectedId);
__selenium_observers__[$$expectedId] = {
observer: new MutationObserver(function(mutations) {
__selenium_observers__[$$expectedId].occured = true;
__selenium_observers__[$$expectedId].observer.disconnect();
}),
occured:false
};
var config = { attributes: true, childList: true, characterData: true, subtree: true };
__selenium_observers__[$$expectedId].observer.observe(target, config);
})();", containerId);
}
public static bool WasContentChanged(this RemoteWebDriver driver, string containerId)
{
return (bool) driver.ExecuteScript( "return window.__selenium_observers__ && window.__selenium_observers__[arguments[0]].occured;", containerId)
}
You can use some kind of timer to asynchronously invoke WasContentChanged method and react for content changes. Please read MutationObserver documentation for more details https://developer.mozilla.org/pl/docs/Web/API/MutationObserver

Related

Change ICN contentViewer's tab title in split pane mode?

I need to change the "title" for each document shown in ICN Viewer, dynamically, at runtime. I'll read the new viewer tab title from the document properties
ENVIRONMENT: ICN 2.0.3 CM8.5 WAS 8.5.5
CODE SO FAR:
I found a PARTIAL solution by hooking "ecm.model.desktop, onChange":
aspect.after(ecm.model.desktop, 'onChange', function() {
var contentViewer = dijit.byId('contentViewer');
if (contentViewer) {
var viewerTabTitleDef = new ViewerTabTitleDef ();
contentViewer.mainTabContainer.getChildren().forEach(function(child) {
viewerTabTitleDef.changeTitle(viewerTabTitleDef.self,
child.controlButton, child.contentViewerPane.viewerItem.item);
});
...
I was able to extend this for subsequent documents opened in the same viewer, and optimized by "removing()" the handler after this initial call. Here is the complete code:
var kill = aspect.after(ecm.model.desktop, 'onChange', function() {
var contentViewer = dijit.byId('contentViewer');
// "contentViewer" will be "unknown" unless viewer invoked
console.log('onChange: contentViewer', contentViewer);
if (contentViewer) {
console.log("new ViewerTabTitleDef()...");
kill.remove();
var viewerTabTitleDef = new ViewerTabTitleDef ();
contentViewer.mainTabContainer.getChildren().forEach(function(child) {
// For initially opened tabs
console.log('initially opened: child', child);
viewerTabTitleDef.changeTitle(viewerTabTitleDef.self, child.controlButton, child.contentViewerPane.viewerItem.item);
});
aspect.after(contentViewer.mainTabContainer, 'addChild', function(child) {
// For tabs added after the viewer was opened
console.log('subsequently opened: child', child);
viewerTabTitleDef.changeTitle(viewerTabTitleDef, child.controlButton, child.contentViewerPane.viewerItem.item);
}, true);
} // end if contentViewer
}); // end aspect.after(onChange desktop)
CURRENT PROBLEM:
Q: How can I change the label for a split tab (either vertical or horizontal)?
So far, I have NOT been able to find any event for any ICN/ECM widget or object variable that I can trigger on.
Thank you in advance!
===============================================
ADDENDUM:
Many thanks to Ivo Jonker, for his suggestion to modify the widget prototype's
"getHtmlName()" method. It worked!
Specifically:
I'm invoking this code from an ICN plugin. I set event handlers in my plugin's base .js file, but it actually gets invoked in the new, separate viewer window.
The original prototype looked like this:
getHtmlName: function() {
var methodName = "getHtmlName";
this.logEntry(methodName);
var displayName = this.item.getDisplayValue("{NAME}");
if (displayName == "") {
displayName = this.item.name;
}
var htmlName = entities.encode(displayName);
this.logExit(methodName);
return htmlName;
},
Per Ivo's suggestion, I overrode the prototype method like this:
myPluginDojo.viewerTabTitleDef = viewerTabTitleDef;
...
ecm.widget.viewer.model.ViewerItem.prototype.getHtmlName = function () {
console.log("NEW getHtmlName()...");
var displayName = myPluginDojo.viewerTabTitleDef.getTitle(this.item);
return displayName;
};
If i understand you correctly, you want to show a different tab-title (instead of the document title) in the navigator viewer whenever a doc is opened?
How about this:
Every document you open in the viewer is wrapped in a ecm.widget.viewer.model.ViewerItem which exposes the getHtmlName that returns the name used in the tab.
Your solution would be to implement your own getHtmlName.
Unfortunately though, the ViewerItem is constructed in the ecm.widget.viewer.ContentViewer#_open and then passed to the ecm.widget.viewer.ContentViewer#_openTab. So you'll either violate best practice by mingling with IBM private method's, or you'll go for a generic approach and just replace the ecm.widget.viewer.model.ViewerItem.prototype.getHtmlName

Wait until page is fully loaded with selenium and intern js

I am trying to create a UI automation test with intern js , but i m getting problem on waiting until the page is fully loaded. My code starts searching for element before the page is loaded. Can some one help me on this.
My code:
define([
'intern!object',
'intern/chai!assert',
'Automation/ConfigFiles/dataurl',
'Automation/pages/login/loginpage',
'intern/dojo/node!fs',
'intern/dojo/node!leadfoot/helpers/pollUntil'
], function (registerSuite, assert,dataurl, LoginPage,fs,pollUntil) {
registerSuite(function () {
var loginPage;
var values;
return {
setup: function () {
var data = fs.readFileSync(loginpage, 'utf8');
json=JSON.parse(data);
console.log('###########Setting Up Login Page Test##########')
this.remote
.get(require.toUrl(json.locator.URL))
.then(pollUntil(this.remote.findById('uname').isDisplayed(),6000)// here i want to wait until page is loaded
.waitForDeletedByClassName('loading').end().sleep(600000)// here i want to wait until loading component is disappered
values = json.values;
loginPage = new LoginPage(this.remote,json.locator);
},
'successful login': function () {
console.log('##############Login Success Test############')
return loginPage
.login(values.unamevalue,values.pwdvalue)
},
// …additional tests…
};
});
});
I m trying to use pollUntil . But I m not sure weather I should use it or not.
pollUntil is a good thing to use here, but it doesn't look like you're actually waiting for polling to finish. Your setup method needs to return the command chain that includes pollUntil so that Intern will know it needs to wait, something like:
var setupPromise = this.remote
.get(require.toUrl(json.locator.URL))...
values = json.values;
loginPage = new LoginPage(this.remote, json.locator);
return setupPromise;
Alternatively, you could pass your LoginPage class the chain:
var setupPromise = this.remote
.get(require.toUrl(json.locator.URL))...
values = json.values;
loginPage = new LoginPage(setupPromise, json.locator);
In this case Intern won't wait for setup to complete, but your LoginPage code will implicitly wait for the setupPromise to complete before doing anything else. While this will work, the intent isn't as clear as in the previous example (e.g., that Intern should wait for some setup process to complete before proceeding).

How to wait for Location Alert ( which is system alert) to show?

I figured out how to dismiss System alert, but I am not able to wait for it to show , since app doesn't see System Alerts. I tried to debug with app.debugDescription and app.alerts.count but no luck.
You should use addUIInterruptionMonitor as #Oletha wrote.
The tricky part here is that system alert buttons don't use Accessibility Identifiers so you have to search for text to tap them. This text is translated to the language you're running your simulator/device, which can be hard if you want to run the test for several languages beside English.
You could use AutoMate framework to simplify this. Here you have an example how to deal with system alerts using AutoMate:
func locationWhenInUse() {
let token = addUIInterruptionMonitor(withDescription: "Location") { (alert) -> Bool in
guard let locationAlert = LocationWhenInUseAlert(element: alert) else {
XCTFail("Cannot create LocationWhenInUseAlert object")
return false
}
locationAlert.allowElement.tap()
return true
}
// Interruption won't happen without some kind of action.
app.tap()
// Wait for given element to appear
wait(forVisibilityOf: locationPage.requestLabel)
removeUIInterruptionMonitor(token)
}
In the example above the locationAlert.allowElement.tap() is possible because AutoMate can handle any language supported by iOS Simulator.
For more examples on how to deal with system alerts using AutoMate please look into: PermissionsTests.swift
Use addUIInterruptionMonitor:withDescription:handler: to register an interruption monitor. To 'wait' for the system alert to appear, use the handler to set a variable when it has been dealt with, and execute a benign interaction with the app when you want to wait for the alert.
You must continue to interact with the app while you are waiting, as interactions are what trigger interruption monitors.
class MyTests: XCTestCase {
let app = XCUIApplication()
func testLocationAlertAppears() {
var hasDismissedLocationAlert = false
let monitor = addUIInterruptionMonitor(withDescription: "LocationPermissions") { (alert) in
// Check this alert is the location alert
let location = NSPredicate(format: "label CONTAINS 'Location'")
if alert.staticTexts.element(matching: location).exists {
// Dismiss the alert
alert.buttons["Allow"].tap()
hasDismissedLocationAlert = true
return true
}
return false
}
// Wait for location alert to be dismissed
var i = 0
while !hasDismissedLocationAlert && i < 20 {
// Do some benign interaction
app.tap()
i += 1
}
// Clean up
removeUIInterruptionMonitor(monitor)
// Check location alert was dismissed
XCTAssertTrue(hasDismissedLocationAlert)
}
}

How do I determine open/closed state of a dijit dropdownbutton?

I'm using a dijit DropDownButton with an application I'm developing. As you know, if you click on the button once, a menu appears. Click again and it disappears. I can't seem to find this in the API documentation but is there a property I can read to tell me whether or not my DropDownButton is currently open or closed?
I'm trying to use a dojo.connect listener on the DropDownButton's OnClick event in order to perform another task, but only if the DropDownButton is clicked "closed."
THANK YOU!
Steve
I had a similar problem. I couldn't find such a property either, so I ended up adding a custom property dropDownIsOpen and overriding openDropDown() and closeDropDown() to update its value, like this:
myButton.dropDownIsOpen = false;
myButton.openDropDown = function () {
this.dropDownIsOpen = true;
this.inherited("openDropDown", arguments);
};
myButton.closeDropDown = function () {
this.dropDownIsOpen = false;
this.inherited("closeDropDown", arguments);
};
You may track it through its CSS classes. When the DropDown is open, the underlying DOM node that gets the focus (property focusNode) receives an additional class, dijitHasDropDownOpen. So, for your situation:
// assuming "d" is a dijit.DropDownButton
dojo.connect(d, 'onClick', function() {
if (dojo.hasClass(d.focusNode, 'dijitHasDropDownOpen') === false) {
performAnotherTask(); // this fires only if the menu is closed.
}
});
This example is for dojo 1.6.2, since you didn't specify your version. It can, of course, be converted easily for other versions.

OpenTok - How to publish/unpublish manually?

I looked at these links
http://www.tokbox.com/opentok/api/tools/js/documentation/overview/publish.html
http://www.tokbox.com/opentok/api/tools/js/tutorials/overview
but their are no examples for publishingunpublishing manually, that is, publishing/unpublishing without using 'streamCreated'/'streamDestroyed' event handler respectively.
The reason I want to do this is that I have a button to publish/unpublish so that the user can do it at will.
Is there a way to do this?
Yes and it is very simple. Check out the prepublish source code to see how. There are 2 functions, startPublishing() and stopPublishing() which achieve this.
Primarily they use session.publish(publisher);to publish and session.unpublish(publisher); to unpublish.
Here is code I have used to work off:
// Called by a button to start publishing to the session
function startPublishing() {
if (!publisher) {
var parentDiv = document.getElementById("myCamera");
var publisherDiv = document.createElement('div'); // Create a div for the publisher to replace
publisherDiv.setAttribute('id', 'opentok_publisher');
parentDiv.appendChild(publisherDiv);
var publisherProps = {
width : VIDEO_WIDTH,
height : VIDEO_HEIGHT
};
publisher = TB.initPublisher(apiKey, publisherDiv.id, publisherProps); // Pass the replacement div id and properties
session.publish(publisher);
show('unpublishLink');
hide('publishLink');
}
}
//Called by a button to stop publishing to the session
function stopPublishing() {
if (publisher) {
session.unpublish(publisher);
}
publisher = null;
show('publishLink');
hide('unpublishLink');
}