Selenium
操做headless chrome 推薦WebDriver
是一個W3C標準, 定義了一套檢查和控制用戶代理(好比瀏覽器)的遠程控制接口,各大主流瀏覽器來實現這些接口以便調用控制接口來操做瀏覽器。javascript
Selenium
是一整套的Web自動化測試解決方案,配合WebDrive規範,實現了對各類用戶代理的適配(好比瀏覽器,PhantomJS等),經過操做瀏覽器的WebDriver
接口來實現帶瀏覽器的Web自動化。html
selenium-webdriver
selenium
相關的API文檔java
selenium-webdriver
的JavaScriptAPI文檔node
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的方式不同,其餘調用徹底同樣webpack
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
同時在代碼中引入git
require('chromedriver')
安裝過程添加參數,默認下載地址爲http://chromedriver.storage.googleapis.com
github
npm install chromedriver --chromedriver_cdnurl=https://npm.taobao.org/mirrors/chromedriver
添加以下內容到.npmrc
文件web
chromedriver_cdnurl=https://npm.taobao.org/mirrors/chromedriver
添加環境變量CHROMEDRIVER_CDNURL
chrome
CHROMEDRIVER_CDNURL=https://npm.taobao.org/mirrors/chromedriver npm install chromedriver
chromedriver
文件路徑安裝過程使用配置參數npm
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
是一個能夠運行在瀏覽器端和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
是一個用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 }) }
能夠到這裏,查看chrome相關的karma-launcher,有ChromeHeadless
和ChromeCanaryHeadless
這兩個headless驅動能夠選擇。
npm i webpack karma-webpack babel-core babel-loader babel-preset-es2015
npm i babel-plugin-istanbul
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中尚未找到合適的方式寫出來。