Web自動化之Headless Chrome測試框架集成

使用Selenium操做headless chrome 推薦

簡介

WebDriver是一個W3C標準, 定義了一套檢查和控制用戶代理(好比瀏覽器)的遠程控制接口,各大主流瀏覽器來實現這些接口以便調用控制接口來操做瀏覽器。javascript

Selenium是一整套的Web自動化測試解決方案,配合WebDrive規範,實現了對各類用戶代理的適配(好比瀏覽器,PhantomJS等),經過操做瀏覽器的WebDriver接口來實現帶瀏覽器的Web自動化。html

使用selenium-webdriver

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')
更換獲取源的URL(使用以下任意一種就行)
  • 安裝過程添加參數,默認下載地址爲http://chromedriver.storage.googleapis.comgithub

    npm install chromedriver --chromedriver_cdnurl=https://npm.taobao.org/mirrors/chromedriver
  • 添加以下內容到.npmrc文件web

chromedriver_cdnurl=https://npm.taobao.org/mirrors/chromedriver
  • 添加環境變量CHROMEDRIVER_CDNURLchrome

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 + 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,有ChromeHeadlessChromeCanaryHeadless這兩個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中尚未找到合適的方式寫出來。

參考資料

  1. Automated testing with Headless Chrome

  2. 使用HeadlessChrome作單頁應用SEO

  3. 基於HeadlessChrome的網頁自動化測試系統-FinalTest

  4. 使用 headless chrome進行測試

  5. 使用 headless chrome進行測試

  6. UI自動化測試之Headless browser容器化

  7. 初探 Headless Chrome

  8. Karma原理及論文

  9. karma入門

  10. karma 測試框架的前世此生

相關文章
相關標籤/搜索