是的,你可以扩展动作框架。但是,严格来说,得到类似的东西:
browser.actions().mouseDown(element).sleep(5000).mouseUp(element).perform();
意味着搞乱 Selenium 的胆量。所以,YMMV。
请注意,Protractor documentation 在解释操作时指的是webdriver.WebDriver.prototype.actions,我认为这意味着它不会修改或添加到 Selenium 提供的内容。
webdriver.WebDriver.prototype.actions 返回的对象类是webdriver.ActionSequence。实际导致序列执行任何操作的方法是webdriver.ActionSequence.prototype.perform。在默认实现中,此函数采用调用.sendKeys() 或.mouseDown() 时记录的命令,并让与ActionSequence 关联的驱动程序按顺序安排它们。所以添加一个.sleep 方法不能这样做:
webdriver.ActionSequence.prototype.sleep = function (delay) {
var driver = this.driver_;
driver.sleep(delay);
return this;
};
否则,睡眠会无序。你要做的就是记录你想要的效果,以便稍后执行。
现在,要考虑的另一件事是默认的.perform() 只期望执行webdriver.Command,这是要发送到浏览器的命令。睡觉不是这样的命令之一。所以必须修改.perform() 来处理我们要用.sleep() 记录的内容。在下面的代码中,我选择让.sleep() 记录一个函数并修改.perform() 以处理除webdriver.Command 之外的函数。
这就是整个东西的样子,一旦放在一起。我首先给出了一个使用 Stock Selenium 的示例,然后添加了补丁和一个使用修改后代码的示例。
var webdriver = require('selenium-webdriver');
var By = webdriver.By;
var until = webdriver.until;
var chrome = require('selenium-webdriver/chrome');
// Do it using what Selenium inherently provides.
var browser = new chrome.Driver();
browser.get("http://www.google.com");
browser.findElement(By.name("q")).click();
browser.actions().sendKeys("foo").perform();
browser.sleep(2000);
browser.actions().sendKeys("bar").perform();
browser.sleep(2000);
// Do it with an extended ActionSequence.
webdriver.ActionSequence.prototype.sleep = function (delay) {
var driver = this.driver_;
// This just records the action in an array. this.schedule_ is part of
// the "stock" code.
this.schedule_("sleep", function () { driver.sleep(delay); });
return this;
};
webdriver.ActionSequence.prototype.perform = function () {
var actions = this.actions_.slice();
var driver = this.driver_;
return driver.controlFlow().execute(function() {
actions.forEach(function(action) {
var command = action.command;
// This is a new test to distinguish functions, which
// require handling one way and the usual commands which
// require a different handling.
if (typeof command === "function")
// This puts the command in its proper place within
// the control flow that was created above
// (driver.controlFlow()).
driver.flow_.execute(command);
else
driver.schedule(command, action.description);
});
}, 'ActionSequence.perform');
};
browser.get("http://www.google.com");
browser.findElement(By.name("q")).click();
browser.actions().sendKeys("foo")
.sleep(2000)
.sendKeys("bar")
.sleep(2000)
.perform();
browser.quit();
在我的 .perform() 实现中,我已将 Selenium 代码使用的 goog... 函数替换为普通 JavaScript。