cndavy

导航

 

首页

Protractor端到端的AngularJS测试框架教程

2014年01月18日 分类:教程JavaScriptAngularJS

Protractor是一个建立在WebDriverJS基础上的端到端(E2E)的AngularJS JavaScript Web应用程序测试框架。Protractor全自动化真实的模拟用户在真正的浏览器中操作、运行并测试开发者的应用程序。

安装Protractor和WebDriver

通过npm进行全局安装protractor Node.js模块:

$ npm install -g protractor@canary 或 $ sudo npm install -g protractor@canary

通过webdriver-manager安装测试驱动及服务器:

webdriver-manager update

启动Selenium测试服务器

在另一个命令行控制台启动Selenium测试服务器:

webdriver-manager start

默认情况下,Selenium测试服务器接入地址为:http://localhost:4444/wd/hub

选用Mocha测试框架

通过npm进行全局安装chai Node.js模块:

npm install -g mocha

使用chai断言库

通过npm进行全局安装mocha Node.js模块:

npm install -g chai-as-promised

使用chai-as-promised异步代码增强插件

通过npm进行全局安装mocha Node.js模块:

npm install -g chai-as-promised

配置AngularJS测试用例

本位使用以下配置通过Chrome浏览器测试AngularJS应用程序:

exports.config = {
  // Selenium server 测试服务器接入地址
  SeleniumAddress: 'http://localhost:4444/wd/hub',

  // 告知测试服务器的配置信息
  capabilities: {
    // 告知需要测试的浏览器类型:可以是 chrome、safari等
    'browserName': 'chrome'
  },

  // 需要运行的测试程序代码文件列表
  specs: ['angularjs-e2e-spec.js'],

  // 选择使用 Mocha 作为JavaScript语言的测试框架
  framework: 'mocha'

};

将上述配置代码保存并命名为conf.js

编写AngularJS测试程序代码

var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
var expect = chai.expect;

describe('angularjs 首页', function() {
  it('应该欢迎一个具名的用户', function() {
    //要求浏览器访问网址http://www.angularjs.org
    browser.get('http://www.angularjs.org');

    //找到ng-model名为'youname'的HTML元素,要求浏览器键入名字
    element(by.model('yourName')).sendKeys('tanshuai');

    var greeting = element(by.binding('yourName'));

     //取得结果并作断言测试
    expect(greeting.getText()).to.eventually.equal('Hello tanshuai!');
  });

  describe('待办事项', function() {
    var todoList;

    beforeEach(function() {
      browser.get('http://www.angularjs.org');

      todoList = element.all(by.repeater('todo in todos'));
    });

    it('应该列出待办事项列表', function() {
      expect(todoList.count()).to.eventually.equal(2);
      expect(todoList.get(1).getText()).to.eventually.equal('build an angular app');
    });

    it('应该添加一个待办事项', function() {
      var addTodo = element(by.model('todoText'));
      var addButton = element(by.css('[value="add"]'));

      addTodo.sendKeys('编写一个Protractor测试');
      addButton.click();

      expect(todoList.count()).toEqual(3);
      expect(todoList.get(2).getText()).to.eventually.equal('编写一个Protractor测试');
    });
  });
});

将上述配置代码保存并命名为angularjs-e2e-spec.js

运行Protractor测试

运行指令:

protractor conf.js

相应的浏览器会被打开,载入网址网页完成后,即开始执行angularjs-e2e--spec.js测试程序。注意 www.angularjs.org 网站含有一些被审查的网址,因此国内载入等待较长,可能因超时导致测试失败,建议此时启用VPN连接该网站。

Protractor API应用程序接口

Protractor代码继承了WebDriver,因此任何WebDriver所具有的函数等均对Protractor有效。

WebDriver与Protractor类

  • get(string)

要求浏览器访问网址 string

关于教程

作者:tanshuai,电邮: i@tanshuai.com

为了更好的服务于开发者,本教程将会持续更新,勘误并完善内容。若发现本文的错误,建议或意见均可联系本文作者。

分享本文

  TANSHUAI © 2016

 
posted on 2016-03-09 14:42  cndavy  阅读(601)  评论(0编辑  收藏  举报