当前位置: 首页 > 文档资料 > Electron 中文文档 >

使用 Selenium 和 WebDriver

优质
小牛编辑
123浏览
2023-12-01

引自 ChromeDriver - WebDriver for Chrome:

WebDriver 是一款开源的支持多浏览器的自动化测试工具。 它提供了操作网页、用户输入、JavaScript 执行等能力。 ChromeDriver 是一个实现了 WebDriver 与 Chromium 联接协议的独立服务。 它也是由开发了 Chromium 和 WebDriver 的团队开发的。

Using Selenium and WebDriver

From ChromeDriver - WebDriver for Chrome:

WebDriver is an open source tool for automated testing of web apps across many browsers. It provides capabilities for navigating to web pages, user input, JavaScript execution, and more. ChromeDriver is a standalone server which implements WebDriver's wire protocol for Chromium. It is being developed by members of the Chromium and WebDriver teams.

配置 Spectron

Spectron 是 Electron 官方支持的 ChromeDriver 测试框架。 它是建立在 WebdriverIO 的顶层,并且 帮助你在测试中访问 Electron API 和绑定 ChromeDriver。

$ npm install --save-dev spectron
// 一个简单的验证测试和一个带标题的可是窗口
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)

Setting up Spectron

Spectron is the officially supported ChromeDriver testing framework for Electron. It is built on top of WebdriverIO and has helpers to access Electron APIs in your tests and bundles ChromeDriver.

$ npm install --save-dev spectron
// A simple test to verify a visible window is opened with a title
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 {
    // Check if the window is visible
    const isVisible = await app.browserWindow.isVisible()
    // Verify the window is visible
    assert.strictEqual(isVisible, true)
    // Get the window's title
    const title = await app.client.getTitle()
    // Verify the window's title
    assert.strictEqual(title, 'My App')
  } catch (error) {
    // Log any failures
    console.error('Test failed', error.message)
  }
  // Stop the application
  await app.stop()
}
verifyWindowIsVisibleWithTitle(myApp)

通过 WebDriverJs 配置

WebDriverJs 是一个可以配合 WebDriver 做测试的 node 模块,我们会用它来做个演示。

Setting up with WebDriverJs

WebDriverJs provides a Node package for testing with web driver, we will use it as an example.

1. 启动 ChromeDriver

首先,你要下载 chromedriver,然后运行以下命令:

$ npm install electron-chromedriver
$ ./node_modules/.bin/chromedriver
Starting ChromeDriver (v2.10.291558) on port 9515
Only local connections are allowed.

记住 9515 这个端口号,我们后面会用到

1. Start ChromeDriver

First you need to download the chromedriver binary, and run it:

$ npm install electron-chromedriver
$ ./node_modules/.bin/chromedriver
Starting ChromeDriver (v2.10.291558) on port 9515
Only local connections are allowed.

Remember the port number 9515, which will be used later

2. 安装 WebDriverJS

$ npm install selenium-webdriver

2. Install WebDriverJS

$ npm install selenium-webdriver

3. 连接到 ChromeDriver

在 Electron 下使用 selenium-webdriver 和其平时的用法并没有大的差异,只是你需要手动设置连接 ChromeDriver,以及 Electron 的路径:

const webdriver = require('selenium-webdriver')
const driver = new webdriver.Builder()
  // "9515" 是ChromeDriver使用的端口
  .usingServer('http://localhost:9515')
  .withCapabilities({
    chromeOptions: {// 这里设置Electron的路径binary: '/Path-to-Your-App.app/Contents/MacOS/Electron'
    }
  })
  .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(() => {
  return driver.getTitle().then((title) => {
    return title === 'webdriver - Google Search'
  })
}, 1000)
driver.quit()

3. Connect to ChromeDriver

The usage of selenium-webdriver with Electron is the same with upstream, except that you have to manually specify how to connect chrome driver and where to find Electron's binary:

const webdriver = require('selenium-webdriver')
const driver = new webdriver.Builder()
  // The "9515" is the port opened by chrome driver.
  .usingServer('http://localhost:9515')
  .withCapabilities({
    chromeOptions: {// Here is the path to your Electron binary.binary: '/Path-to-Your-App.app/Contents/MacOS/Electron'
    }
  })
  .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(() => {
  return driver.getTitle().then((title) => {
    return title === 'webdriver - Google Search'
  })
}, 1000)
driver.quit()

通过 WebdriverIO 配置

WebdriverIO 也是一个配合 WebDriver 用来测试的 node 模块.

Setting up with WebdriverIO

WebdriverIO provides a Node package for testing with web driver.

1. 启动 ChromeDriver

首先,你要下载 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 这个端口号,我们后面会用到

1. Start ChromeDriver

First you need to download the chromedriver binary, and run it:

$ 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.

Remember the port number 9515, which will be used later

2. 安装 WebdriverIO

$ npm install webdriverio

2. Install WebdriverIO

$ npm install webdriverio

3. 连接到 chrome driver

const webdriverio = require('webdriverio')
const options = {
  host: 'localhost', // Use localhost as chrome driver server
  port: 9515, // "9515" is the port opened by chrome driver.
  desiredCapabilities: {
    browserName: 'chrome',
    chromeOptions: {binary: '/Path-to-Your-App/electron', // Electron的路径args: [/* cli arguments */] // Optional, perhaps 'app=' + /path/to/your/app/
    }
  }
}
let client = webdriverio.remote(options)
client
  .init()
  .url('http://google.com')
  .setValue('#q', 'webdriverio')
  .click('#btnG')
  .getTitle().then((title) => {
    console.log('Title was: ' + title)
  })
  .end()

3. Connect to chrome driver

const webdriverio = require('webdriverio')
const options = {
  host: 'localhost', // Use localhost as chrome driver server
  port: 9515, // "9515" is the port opened by chrome driver.
  desiredCapabilities: {
    browserName: 'chrome',
    chromeOptions: {binary: '/Path-to-Your-App/electron', // Path to your Electron binary.args: [/* cli arguments */] // Optional, perhaps 'app=' + /path/to/your/app/
    }
  }
}
let client = webdriverio.remote(options)
client
  .init()
  .url('http://google.com')
  .setValue('#q', 'webdriverio')
  .click('#btnG')
  .getTitle().then((title) => {
    console.log('Title was: ' + title)
  })
  .end()

工作流

无需重新编译 Electron,只要把 app 的源码放到 Electron的资源目录 里就可直接开始测试了。

当然,你也可以在运行Electron时传入参数指定你的应用所在文件夹。这样可以免去拷贝粘贴应用到Electron资源目录的步骤。

Workflow

To test your application without rebuilding Electron, place your app source into Electron's resource directory.

Alternatively, pass an argument to run with your Electron binary that points to your app's folder. This eliminates the need to copy-paste your app into Electron's resource directory.