硒:是否有类似“在DOM中插入新元素"之类的事件? [英] Selenium: are there events like "New element inserted in DOM"

查看:74
本文介绍了硒:是否有类似“在DOM中插入新元素"之类的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试的站点具有通知逻辑,该通知逻辑会在屏幕底部显示一条消息,将其保留一秒钟,然后将其发送出去.显示通知时,它会隐藏其他元素,这会使我的测试不稳定.我尽力弄清何时显示通知(当业务逻辑显示通知时)并将其关闭,但是我时不时地发现新情况,我的代码不知道何时显示通知.

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.

是否有一种方法(使用Selenium)来订阅诸如在DOM中插入新元素"之类的事件.在其回调中取消通知将一劳永逸地解决我的问题.

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不支持此用例,但您可以使用javascript中的MutationObserver来实现.我不知道您使用什么语言编写硒测试,但是在C#中,您可以按照以下方法创建扩展方法

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)
}

您可以使用某种计时器来异步调用WasContentChanged方法并对内容更改作出反应.请阅读MutationObserver文档以获取更多详细信息 https://developer.mozilla.org/pl/docs/Web/API/MutationObserver

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

这篇关于硒:是否有类似“在DOM中插入新元素"之类的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆