使用 Selenium 和 WebDriver
是 Electron 官方支持的 ChromeDriver 测试框架。 它是建立在 WebdriverIO 的顶层,并且 帮助你在测试中访问 Electron API 和绑定 ChromeDriver。
const Application = require('spectron').Application
const assert = require('assert')
const myApp = new Application({
path: '/Applications/MyApp.app/Contents/MacOS/MyApp'
})
const verifyWindowIsVisibleWithTitle = async (app) => {
await app.start()
try {
const isVisible = await app.browserWindow.isVisible()
// 验证窗口是否可见
assert.strictEqual(isVisible, true)
// 获取窗口标题
const title = await app.client.getTitle()
// 验证窗口标题
assert.strictEqual(title, 'My App')
} catch (error) {
console.error('Test failed', error.message)
}
// 停止应用
await app.stop()
}
verifyWindowIsVisibleWithTitle(myApp)
是一个可以配合 WebDriver 做测试的 node 模块,我们会用它来做个演示。
记住 9515
这个端口号,我们后面会用到
$ npm install selenium-webdriver
在 Electron 下使用 selenium-webdriver
和其平时的用法并没有大的差异,只是你需要手动设置连接 ChromeDriver,以及 Electron 的路径:
WebdriverIO 也是一个配合 WebDriver 用来测试的 node 模块.
1. 启动 ChromeDriver
$ npm install electron-chromedriver
$ ./node_modules/.bin/chromedriver --url-base=wd/hub --port=9515
Starting ChromeDriver (v2.10.291558) on port 9515
Only local connections are allowed.
记住 9515
这个端口号,我们后面会用到
3. 连接到 chrome 驱动
const options = format@@
端口:9515, // "9515" 是由chrome驱动程序打开的端口。
desiredCapabilities: {
browserName: 'chrome',
'goog:chromeOptions': {
binary: '/Path-to-Your-App/electron', // Path to your Electron binary.
args: [/* cli 参数 */] // 可选, 也许'app=' + /path/to/your/app/
}
}
const 客户端 = webdriverio。 emote(选项)
客户端
.init()
. rl('http://google.com')
.setValue('#q', 'webdriverio')
.click('#btnG')
.getTitle(). hen(title) => @un.org
console.log('title was: ' + title)
.end()
无需重新编译 Electron,只要把 app 的源码 Electron的资源目录 里就可直接开始测试了。
或者,传递一个参数,与您的 Electron 二进制运行,指向您的 个应用文件夹。 这就消除了将您的应用复制粘贴到 Electron 资源目录的必要性。