6.5. Node.js selenium-webdriver
下载 Selenium Serverhttp://selenium-release.storage.googleapis.com/2.40/selenium-server-standalone-2.40.0.jar
启动 Selenium Server
java -jar selenium-server-standalone-2.40.0.jar
CentOS 6.5
# yum install nodejs npm # npm -g install selenium-webdriver
默认node_modules安装在 /usr/lib/node_modules/selenium-webdriver
Ubuntu 13.04
sudo apt-get install nodejs sudo apt-get install npm sudo npm -g install selenium-webdriver
默认node_modules安装在 /usr/local/lib/node_modules/selenium-webdriver
不是用-g参数npm install selenium-webdriver 将会安装在当前目录下
远程控制Chrome参考
https://code.google.com/p/selenium/wiki/ChromeDriver下载后解压运行里面的可执行文件
var driver = new webdriver.Builder().usingServer('http://192.168.6.20:9515/').withCapabilities(webdriver.Capabilities.chrome()).build();
Firefox 使用
var driver = new webdriver.Builder().usingServer('http://192.168.6.20:4444/wd/hub').withCapabilities(webdriver.Capabilities.firefox()).build();
例 6.3. Node.js selenium-webdriver 本地测试
selenium-server-standalone 与 测试脚本在同一台机器上
var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); driver.get('http://www.google.com'); driver.findElement(webdriver.By.name('q')).sendKeys('webdriver'); driver.findElement(webdriver.By.name('btnK')).click(); driver.wait(function() { return driver.getTitle().then(function(title) { return title === 'webdriver - Google Search'; }); }, 1000); driver.quit();
例 6.4. NODE.JS selenium-webdriver 远程测试
从一台测试机遥控另台selenium-server-standalone
var webdriver = require('/usr/local/lib/node_modules/selenium-webdriver'); var builder = new webdriver.Builder(). usingServer('http://192.168.6.20:4444/wd/hub'). withCapabilities(webdriver.Capabilities.firefox()); var driver = builder.build(); driver.get('http://www.google.com'); driver.findElement(webdriver.By.name('q')).sendKeys('webdriver'); driver.findElement(webdriver.By.name('btnK')).click(); driver.wait(function() { return driver.getTitle().then(function(title) { return title === 'webdriver - Google Search'; }); }, 1000); driver.quit();
安装 mocha
npm install -g mocha
测试脚本
var assert = require('assert'), test = require('selenium-webdriver/testing'), webdriver = require('selenium-webdriver'); test.describe('Google Search', function() { test.it('should work', function() { //var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build(); var driver = new webdriver.Builder().usingServer('http://192.168.6.20:4444/wd/hub').withCapabilities(webdriver.Capabilities.firefox()).build(); driver.get('http://www.google.com'); var searchBox = driver.findElement(webdriver.By.name('q')); searchBox.sendKeys('simple programmer'); searchBox.getAttribute('value').then(function(value) { assert.equal(value, 'simple programmer'); }); driver.quit(); }); });
运行测试程序
# mocha mocha.js 1 passing (10s)
测试成功返回1 passing (10s)