Web自动化之Headless Chrome测试框架集成
使用Selenium
操作headless chrome 推荐
简介
WebDriver
是一个W3C标准, 定义了一套检查和控制用户代理(比如浏览器)的远程控制接口,各大主流浏览器来实现这些接口以便调用控制接口来操作浏览器。
Selenium
是一整套的Web自动化测试解决方案,配合WebDrive规范,实现了对各种用户代理的适配(比如浏览器,PhantomJS等),通过操作浏览器的WebDriver
接口来实现带浏览器的Web自动化。
使用selenium-webdriver
selenium
相关的API文档selenium-webdriver
的JavaScriptAPI文档
const webdriver = require('selenium-webdriver'),
By = webdriver.By;
const driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
driver.get('https://www.baidu.com').then((args) => {
// 获取百度搜索按钮的 文本
driver.findElement(By.id('su')).then((element) => {
return element.getAttribute('value')
}).then((btnName) => {
console.log(btnName)
});
// 获取百度首页 title
driver.getTitle().then((title) => {
console.log(title);
});
});
driver.quit();
使用browserstack-webdriver
只是获取driver的方式不一样,其他调用完全一样
const webdriver = require('browserstack-webdriver'),
By = webdriver.By;
// Input capabilities
const capabilities = {
'browserName' : 'firefox',
'browserstack.user' : BROWSERSTACK_USERNAME,
'browserstack.key' : BROWSERSTACK_KEY
}
const driver = new webdriver.Builder().
usingServer('http://hub.browserstack.com/wd/hub').
withCapabilities(capabilities).
build();
driver.get('https://www.baidu.com').then((args) => {
// 获取百度搜索按钮的 文本
driver.findElement(By.id('su')).then((element) => {
return element.getAttribute('value')
}).then((btnName) => {
console.log(btnName)
});
// 获取百度首页 title
driver.getTitle().then((title) => {
console.log(title);
});
});
driver.quit();
使用 chromedriver
chromedriver
是一个编码辅助,自动配置环境变量,不需要手动下载和配置环境变量,通过安装chromedriver
同时在代码中引入
require('chromedriver')
更换获取源的URL(使用如下任意一种就行)
安装过程添加参数,默认下载地址为
http://chromedriver.storage.googleapis.com
npm install chromedriver --chromedriver_cdnurl=https://npm.taobao.org/mirrors/chromedriver
添加如下内容到
.npmrc
文件
chromedriver_cdnurl=https://npm.taobao.org/mirrors/chromedriver
- 添加环境变量
CHROMEDRIVER_CDNURL
CHROMEDRIVER_CDNURL=https://npm.taobao.org/mirrors/chromedriver npm install chromedriver
更换安装的chromedriver
文件路径
- 安装过程使用配置参数
npm install chromedriver --chromedriver_filepath=/path/to/chromedriver_mac64.zip
- 添加如下内容到
.npmrc
文件
chromedriver_filepath=/path/to/chromedriver_mac64.zip
- 添加环境变量
CHROMEDRIVER_FILEPATH=/path/to/chromedriver_mac64.zip
使用mocha + chai
简介
mocha
是一个可以运行在浏览器端和NodeJS环境的JavaScript测试框架,区别于类库,框架定义好了流程,并调用你的代码。
chai
是一个断言库,判断结果是否符合预期。
实例代码
const chai = require('chai');
const chromeDriver = require('selenium-webdriver/chrome')
const webdriver = require('selenium-webdriver'),
By = webdriver.By;
const driver = new webdriver.Builder()
.forBrowser('chrome')
.setChromeOptions(new chromeDriver.Options().addArguments(['headless']))
.build();
describe('首页加载测试',function(){
// 获取百度搜索按钮的 文本
describe('按钮文本',function(){
it('按钮文本必须等于',function(done){
driver.get('https://www.baidu.com').then(function(){
driver.findElement(By.id('su')).then((element) => {
return element.getAttribute('value')
}).then((btnName) => {
console.log(btnName);
chai.expect(btnName).to.equal('百度一下');
done();
});
});
})
});
// 获取百度首页 title
describe('首页标题',function(){
it('首页标题应该为',function(done){
driver.get('https://www.baidu.com').then(function(){
driver.getTitle().then((title) => {
console.log(title);
chai.expect(title).to.equal('百度一下,你就知道');
done();
});
});
});
});
after(function(){
driver.quit();
})
});
使用Karma + mocha + chai
简介
Karma
是一个用JavaScript实现的测试执行器,实现了如下内容
安装相应的依赖库
npm i --save-dev karma karma-chrome-launcher karma-mocha karma-chai
npm i --save-dev mocha chai
生成配置文件
在工程目录下执行如下命令
./node_modules/.bin/karma init
一路按照提示操作即可,生成的配置文件在工程目录下karma.conf.js
,内容大致如下:
// Karma configuration
// Generated on Mon Jul 10 2017 19:49:48 GMT+0800 (CST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
调整配置支持headless chrome
可以到这里,查看chrome相关的karma-launcher,有ChromeHeadless
和ChromeCanaryHeadless
这两个headless驱动可以选择。
调整配置支持ES6,添加webpack
npm i webpack karma-webpack babel-core babel-loader babel-preset-es2015
调整配置增加测试覆盖度
npm i babel-plugin-istanbul
最终的到的Karma配置文件
karma.conf.js
// Karma configuration
// Generated on Mon Jul 10 2017 19:49:48 GMT+0800 (CST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha','chai'],
// list of files / patterns to load in the browser
files: [
'test/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/**/*.js': ['webpack']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
coverageReporter: {
type: 'html',
dir: 'coverage/'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['ChromeHeadless'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
webpack: {
module: {
loaders: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015'],
plugins: ['istanbul']
}
}]
}
}
})
}
编写代码
src/index.js
const isType = (data, type) => {
return ['[object ', type, ']'].join('') === Object.prototype.toString.call(data)
};
const isFunction = (data) => {
return isType(data, 'Function')
};
const isArray = (data) => {
return isType(data, 'Array')
};
module.exports = {
isType,
isFunction,
isArray
}
编写测试用例
test/index.js
const typeUtil = require('../src/index')
describe('index.js: ', () => {
it('isFunction() should work fine.', () => {
expect(typeUtil.isFunction(function(){})).to.equal(true)
expect(typeUtil.isFunction(Object.prototype.toString)).to.equal(true)
});
it('isArray() should work file.', () => {
expect(typeUtil.isArray([])).to.equal(true)
expect(typeUtil.isArray({})).to.equal(false)
})
});
运行测试
- 在当前目录下运行
./node_modules/.bin/karma start
- 或者添加如下代码到
package.json
"scripts": {
"test": "karma start"
}
然后运行npm run test
查看结果
- 命令行能看到运行结果
- 在工程目录下的
coverage
目录能看到相应的覆盖率报告
存在的问题
Karma是将测试Case在浏览器中运行并查看结果,当页面的url 改变的时候,会影响到整个Karma的执行,会有类似Some of your tests did a full page reload!
这样的提示。上面打开百度首页检查按钮和title的例子在Karma中还没有找到合适的方式写出来。
参考资料
- Automated testing with Headless Chrome
- 使用HeadlessChrome做单页应用SEO
- 基于HeadlessChrome的网页自动化测试系统-FinalTest
- 使用 headless chrome进行测试
- 使用 headless chrome进行测试
- UI自动化测试之Headless browser容器化
- 初探 Headless Chrome
- Karma原理及论文
- karma入门
- karma 测试框架的前世今生
Web自动化之Headless Chrome测试框架集成的更多相关文章
- Web自动化之Headless Chrome概览
Web自动化 这里所说的Web自动化是所有跟页面相关的自动化,比如页面爬取,数据抓取,页面内容检测,页面功能测试,页面加载性能测试,页面回归测试等等,当前主要由如下几种解决方式: 文本数据获取 这就是 ...
- Web自动化之Headless Chrome编码实战
API 概览 && 编码Tips 文档地址 github Chrome DevTools Protocol 协议本身的仓库 有问题可以在这里提issue github debugger ...
- Web自动化之Headless Chrome开发工具库
命令行运行Headless Chrome Chrome 安装(需要带梯子) 下载地址 几个版本的比较 Chromium 不是Chrome,但Chrome的内容基本来源于Chromium,这个是开源的版 ...
- 自动化移动安全渗透测试框架:Mobile Security Framework
自动化移动安全渗透测试框架:Mobile Security Framework 译/Sphinx 测试开发社区 7月3日 Mobile Security Framework (移动安全框架) 是一 ...
- Selenium3+python自动化014-自动化测试框架的作用
1.能够有效组织和管理测试脚本 2.进行数据驱动或者关键字驱动的测试 3.将基础的测试代码进行封装,降低测试脚本编写的复杂性和重复性 4.提高测试脚本维护和修改的效率 5.自动执行测试脚本,并自动发布 ...
- 基于python的unittest测试框架集成到jenkins(Mac)
1.jenkins部分 1.1 安装jenkins jenkins下载地址:https://jenkins.io/download/ 安装步骤,疯狂点击下一步 1.2 打开jenkins服务 在浏览器 ...
- Web自动化必会知识:「Web基础、元素定位、元素操作、Selenium运行原理、项目实战+框架」
1.web 基础-html.dom 对象.js 基本语法 Dom 对象里面涉及元素定位以及对元素的修改.因为对元素操作当中涉及的一些 js 操作,js 基本语法要会用.得要掌握前端的基本用法.为什么要 ...
- Selenium 4 Java的最佳测试框架
几十年来,Java一直是开发应用程序服务器端的首选编程语言.尽管JUnit一直在与开发人员一起帮助他们进行自动化的单元测试,但随着时间的推移和测试行业的发展,特别是伴随着自动化测试的兴起,已经开发了许 ...
- Cypress与TestCafe WebUI端到端测试框架简介
近期接触了Cypress和TestCafe,两个测试框架都基于Node.js,都不再使用Selenium+WebDriver,而且开箱即用,非常轻量级,就冲着不再使用WebDriver这一点,极大地勾 ...
随机推荐
- mysql 列转行,合并字段
数据表: 列转行:利用max(case when then) max---聚合函数 取最大值 (case course when '语文' then score else 0 end) ---判断 ...
- android EditText设置
EditText输入的文字为电话号码 Android:phoneNumber=”true” //输入电话号码 //自动弹出键盘 ((InputMethodManager)getSystemServi ...
- Asp.net core 2.0.1 Razor 的使用学习笔记(四)
ASP.net core 2.0.1 中 asp.net identity 2.0.1 的基本使用(三)—用户注册 一.修改用户注册 1.打开Pages文件夹>Account>Regist ...
- 结合find和cp批量查找文件并复制到指定文件夹中
find . -name JA1_*001_027 | xargs -i cp {} F:/ 说明: . 表示当前文件夹及其子文件夹中查找 -name 指定待查找文件,可以使用通配符 F:/ 表示 ...
- JS小练习1
要求: 一.定义"改变颜色"的函数 二.定义"改变宽高"的函数 三.定义"隐藏内容"的函数 四.定义"显示内容"的函数 ...
- ubuntu下进入root错误解决方法
1.进入root用户提示su: Authentication failure roots@ubuntu:~$ su - Password: su: Authentication failure 2.通 ...
- ATS 分级缓存
理解缓存分级cache hierarchies 缓存分级是由彼此能够相互通信的各级缓存组成的,ATS支持几种类型的缓存分级.所有的缓存分级都有父子缓存概念. 父缓存位于缓存分级的较高级别,ATS能将请 ...
- Jmeter之性能测试类型
pipe-clean test 在测试环境预先跑 确定脚本准确性 单用户跑 获取baseline 容量测试 经典的性能测试类型 获取系统稳定运行时最大的吞吐量/并发数/响应时间时 尽量模拟真实情况 ...
- 05_Linux网络配置及CRT远程
占位占位占位占位占位占位占位占位
- 给file_get_contents函数设置超时时间
$opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60, ) ); $context = str ...