三、测试实例
以下是用BDD写的一个测试示例test.js,该测试的目的是打开google主页,搜索mocha,并检查搜索结果网页的title是否含有mocha关键字。
1 var should = require('chai').should(); 2 var webdriver = require('selenium-webdriver'); 3 var By = webdriver.By; 4 5 var builder = new webdriver.Builder().usingServer("http://127.0.0.1:4444/wd/hub"); 6 builder.withCapabilities({ browserName : "firefox" }); 7 var driver = builder.build(); 8 9 describe ('first test', function () { 10 beforeEach(function () { 11 driver.get('http://www.google.com'); 12 }); 13 14 afterEach(function () { 15 driver.close(); 16 driver.quit(); 17 }); 18 19 it('should have correct title', function (done) { 20 driver.findElement(By.css('#lst-ib')).sendKeys('mocha'); 21 driver.findElement(By.css('[name="btnK"]')).click(); 22 driver.sleep(3000); 23 driver.getTitle().then(function (title) { 24 title.should.contain('mocha'); 25 done(); 26 }); 27 }); 28 }); |
在命令行中切换到测试目录,如本例中新建的mocha-test目录,输入以下命令以启动测试:
mocha -t 30000 -R spec test.js
该命令中的"-t 30000"是设置一个测试用例(一个it函数表示一个测试用例)运行的时间不超过30秒,"-R spec"是设置测试结果的输出格式。关于mocha运行测试的更多参数不再赘述。