WebDriver 是一款开源的支持多浏览器的自动化测试工具。它提供了操作网页、用户输入、JavaScript 执行等能力。ChromeDriver 是一个实现了 WebDriver 与 Chromium 联接协议的独立服务。它也是由开发了 Chromium 和 WebDriver 的团队开发的。
$ npm install --save-dev spectron
// 一个简单的测试验证一个带标题的可见的窗口
var Application = require('spectron').Application
var assert = require('assert')
var app = new Application({
path: '/Applications/MyApp.app/Contents/MacOS/MyApp'
})
app.start().then(function () {
// 检查浏览器窗口是否可见
return app.browserWindow.isVisible()
}).then(function (isVisible) {
// 验证浏览器窗口是否可见
assert.equal(isVisible, true)
}).then(function () {
// 获得浏览器窗口的标题
return app.client.getTitle()
}).then(function (title) {
// 验证浏览器窗口的标题
assert.equal(title, 'My App')
}).catch(function (error) {
// 记录任何错误
console.error('Test failed', error.message)
}).then(function () {
// 停止应用程序
return app.stop()
})
$ ./chromedriver
Starting ChromeDriver (v2.10.291558) on port 9515
Only local connections are allowed.
$ npm install selenium-webdriver
const webdriver = require('selenium-webdriver')
var driver = new webdriver.Builder()
// "9515" 是ChromeDriver使用的端口
.usingServer('http://localhost:9515')
.withCapabilities({
chromeOptions: {
// 这里设置Electron的路径
binary: '/Path-to-Your-App.app/Contents/MacOS/Atom'
}
})
.forBrowser('electron')
.build()
driver.get('http://www.google.com')
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver')
driver.findElement(webdriver.By.name('btnG')).click()
driver.wait(function () {
return driver.getTitle().then(function (title) {
return title === 'webdriver - Google Search'
})
}, 1000)
driver.quit()
$ chromedriver --url-base=wd/hub --port=9515
Starting ChromeDriver (v2.10.291558) on port 9515
Only local connections are allowed.
$ npm install webdriverio
const webdriverio = require('webdriverio')
const options = {
host: 'localhost', // 使用localhost作为ChromeDriver服务器
port: 9515, // "9515"是ChromeDriver使用的端口
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {
binary: '/Path-to-Your-App/electron', // Electron的路径
args: [/* cli arguments */] // 可选参数,类似:'app=' + /path/to/your/app/
}
}
}
let client = webdriverio.remote(options)
client
.init()
.url('http://google.com')
.setValue('#q', 'webdriverio')
.click('#btnG')
.getTitle().then(function (title) {
console.log('Title was: ' + title)
})
.end()