入門:前端自動化測試karma,Backstopjs,Selenium-webdriver,Mocha

前言:

最近在學習前端自動化測試,接觸了不少測試框架,Karma+Jasmine+karma-coverage:單元測試和測試代碼覆蓋率、Backstopjs:css迴歸測試、Selenium-webdriver:e2e測試、Mocha+chai:異步測試,遇到過不少坑,勉勉強強總算跑通一個基本流程,如有錯誤,歡迎指出,感謝。javascript

github地址:fetestcss

1.Karma+Jasmine+karma-coverage

單元測試(模塊測試)是開發者編寫的一小段代碼,用於檢驗被測代碼的一個很小的、很明確的功能是否正確。一般而言,一個單元測試是用於判斷某個特定條件(或者場景)下某個特定函數的行爲。
html

Karma是一個基於Node.js的JavaScript測試執行過程管理工具( Test Runner ).。該工具可用於測試全部主流Web瀏覽器, 也可集成到CI ( Continuous integration ) 工具, 也可和其餘代碼編輯器一塊兒使用.。這個測試工具的一個強大特性就是, 它能夠監控(Watch)文件的變化, 而後自行執行。

jasmine 是一個行爲驅動開發(TDD)測試框架, 一個js測試框架,它不依賴於瀏覽器、dom或其餘js框架。具體語法參照:官方api
前端

1.1 使用 Karma 對代碼進行單元測試,首先須要安裝一系列的相關插件。

建立fetest的文件夾,並進入java

安裝karma
node

npm install -g karma-cli複製代碼
npm install karma --save-dev複製代碼

安裝各類相關的插件ios

npm install karma-jasmine karma-phantomjs-launcher jasmine-core --save-dev
複製代碼

初始化,總體的配置選項以下:git

karma init
複製代碼
Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> jasmine

Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no

Do you want to capture any browsers automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> PhantomJS
>
What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
>

Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
>

Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> no複製代碼

啓動karmagithub

karma start複製代碼

出現一下界面表明成功,可進行下一步操做,第一次須要安裝phantomjsweb

npm install -g phantomjs複製代碼


初始化完成以後,會在咱們的項目中生成一個 karma.conf.js 文件,這個文件就是 Karma 的配置文件。

// Karma configuration
// Generated on Sat Jun 02 2018 11:06:15 GMT+0800 (中國標準時間)

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: ['jasmine'], //使用何種斷言庫


    // list of files / patterns to load in the browser
    files: [
       './unit/**/*.js',     //被測試的代碼路徑
       './unit/**/*.spec.js' //測試代碼路徑
    ],


    // list of files / patterns 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: false,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],


    // 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
  })
}複製代碼

建立unit文件夾,並建立index.js、index.spec.js

index.js

function add (num){
    if(num == 1){
        return 1;
    }else{
        return num+1;
    }

}複製代碼

index.spec.js

describe("測試簡單基本函數", function() {
    it("+1測試", function() {
        expect(add(1)).toBe(1);
        expect(add(2)).toBe(5);
    });
});複製代碼

啓動karma

karma start複製代碼

成功了一個,錯誤一個。

1.2 使用 karma-coverage測試代碼覆蓋率

安裝karma-coverage

npm install karma-coverage --save-dev複製代碼

建立一個docs文件夾,用來存放生成的的測試文件,配置 karma.conf.js 文件:

// Karma configuration
// Generated on Sat Jun 02 2018 19:49:27 GMT+0800 (中國標準時間)

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: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
        './unit/**/*.js',
        './unit/**/*.spec.js'
    ],


    // list of files / patterns to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        'unit/**/*.js': ['coverage']//對那些文件生成代碼覆蓋率檢查

    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter

    reporters: ['progress','coverage'],//添加'coverage'

    coverageReporter: {
          type : 'html',           //生成html頁面
          dir : './docs/coverage/' //存放html頁面位置
    },

    // 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: false,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],


    // 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
  })
}
複製代碼

啓動karma

karma start複製代碼

會在docs中生成一個coverage文件夾,裏面有生成的測試代碼覆蓋率的可視化html頁面。


打開index.html


修改index.spec.js

describe("測試簡單基本函數", function() {
    it("+1測試", function() {
        expect(add(1)).toBe(1);
    });
});複製代碼
karma start複製代碼


2.Backstopjs:css迴歸測試

BackstopJS就是一個可以實現css自動化迴歸測試的工具,和Mocha這種依靠JavaScript判斷斷言語句正誤和PhantomJS以模擬用戶操做的測試工具不一樣,BackstopJS是一個基於比較網站快照的變化的迴歸測試工具,所以他更適給項目中的樣式作迴歸測試,能夠確保咱們在重構網站樣式的時候樣式不發生變化,並且他支持設置多種瀏覽器尺寸,能夠測試響應式佈局。

簡單點說:backstopjs,能夠自動的對比UI出的圖與前端寫好的圖,不一致的地方會標出。

BackstopJS具備如下特性:

  • 支持多頁面、多測試用例測試
  • 可使用腳本模擬出用戶的交互動做
  • 提供命令行和瀏覽器兩種形式報告
  • 支持PhantomJS或SlimerJS作瀏覽器引擎,事實上兩種引擎也能夠改造出基於快照對比的迴歸測試方案,可是BackstopJS使用更簡單,而且作到了能夠經過配置切換引擎。
  • 支持設置多種瀏覽器尺寸,方便實現響應式佈局測試
  • 能夠測試HTML5元素,好比網頁字體和Flexbox
  • 提供了擴展接口,可供用戶集成到其餘測試系統中 

安裝BackstopJS

npm install -g backstopjs複製代碼

初始化,會生成配置文件backstop.json和backstop_data文件夾

backstop init複製代碼

配置 backstop.json

{
  "id": "backstop_default",//測試用例id,用於BackstopJS管理和爲文件命名
  "viewports": [
    {
      "label": "phone",//配置手機分辨率
      "width": 375,
      "height": 667
    },
    {
      "label": "tablet",//配置平板分辨率
      "width": 1024,
      "height": 768
    }
  ],
  "onBeforeScript": "puppet/onBefore.js",
  "onReadyScript": "puppet/onReady.js",
 //測試用例  "scenarios": [                     
    {
      "label": "qq.map",//測試用例名
      "cookiePath": "backstop_data/engine_scripts/cookies.json",
      "url": "https://map.baidu.com/mobile/webapp/index/index/",//測試地址
      "referenceUrl": "",
      "readyEvent": "",
      "readySelector": "",
      "delay": 0,
      "hideSelectors": [],
      "removeSelectors": [],
      "hoverSelector": "",
      "clickSelector": "",
      "postInteractionWait": 0,
      "selectors": [],
      "selectorExpansion": true,
      "misMatchThreshold" : 0.1,
      "requireSameDimensions": true
    }
  ],
  "paths": {
    "bitmaps_reference": "backstop_data/bitmaps_reference",//存放測試時的ui給的圖片
    "bitmaps_test": "backstop_data/bitmaps_test",//生成測試時的圖片
    "engine_scripts": "backstop_data/engine_scripts",
    "html_report": "./docs/backstop_data/html_report",//生成測試的html頁面存放路徑
    "ci_report": "backstop_data/ci_report"
  },
  "report": ["browser"],
  "engine": "puppeteer",
  "engineFlags": [],
  "asyncCaptureLimit": 5,
  "asyncCompareLimit": 50,
  "debug": false,
  "debugWindow": false
}複製代碼

我測試的是https://map.baidu.com/mobile/webapp/index/index/騰訊地圖

啓動

backstop test 複製代碼


第一次啓動會顯示下面的錯誤,須要在backstop_data文件夾中建立文件夾bitmaps_reference並在裏面存放對應的測試圖。上面的3張圖分別對應的是測試圖自動截取的網站圖對比圖(粉色區域不一致)


再次啓動

backstop test 複製代碼


3.Selenium-webdriver:e2e測試

Selenium是一個瀏覽器自動化測試庫,大多時候咱們用它來測試web應用,Selenium 能夠勝任任何在瀏覽器上自動化測試的任務。

Webdriver (Selenium2)是一種用於Web應用程序的自動測試工具,它提供了一套友好的API,與Selenium 1(Selenium-RC)相比,Selenium 2的API更容易理解和使用,其可讀性和可維護性也大大提升。Webdriver徹底就是一套類庫,不依賴於任何測試框架,除了必要的瀏覽器驅動,不須要啓動其餘進程或安裝其餘程序,也沒必要須要先啓動服務。

安裝Selenium-webdriver

npm install Selenium-webdriver --save-dev複製代碼

安裝火狐驅動文件,只須要下載解壓到當前目錄則可,下載鏈接:geckodriver(.exe)



建立e2e文件夾,在裏面建立baidu.js

baidu.js       可查看 Selenium-webdriver api

const {Builder, By, Key, until} = require('selenium-webdriver');

(async function example() {
    let driver = await new Builder().forBrowser('firefox').build();
    try {
        await driver.get('https://www.baidu.com/');//打開測試頁面
        await driver.findElement(By.name('wd')).sendKeys('隨風而行', Key.RETURN);//定位某個元素,在輸入框中輸入內容
        await driver.wait(until.titleIs('隨風而行_百度搜索'), 1000);
    } finally {
        await driver.quit();//退出
    }
})();複製代碼

用node來啓動

node ./e2e/baidu.js複製代碼

以後會自動彈出測試,成功退出,報錯會彈出報錯信息,你們能夠自行玩耍。

4.Mocha+chai:異步測試

mocha是一款功能豐富的javascript單元測試框架,支持TDD,BDD等多種接口,它既能夠運行在nodejs環境中,也能夠運行在瀏覽器環境中。
javascript是一門單線程語言,最顯著的特色就是有不少異步執行。同步代碼的測試比較簡單,直接判斷函數的返回值是否符合預期就好了,而異步的函數,就須要測試框架支持回調、promise或其餘的方式來判斷測試結果的正確性了。mocha能夠良好的支持javascript異步的單元測試。
mocha會串行地執行咱們編寫的測試用例,能夠在將未捕獲異常指向對應用例的同時,保證輸出靈活準確的測試結果報告。

安裝mocha ,mochawesome ,chai 

npm install -g mocha 複製代碼
npm install chai mochawesome --save-dev複製代碼

建立mochaRunner.js

const Mocha = require("mocha");
const mocha = new Mocha({
    reporter: 'mochawesome',
    reporterOptions:{
        reporteDir:"./docs/mochawesome-reporter" //生成測試頁面路徑
    }
});
mocha.addFile('./service/router.spec.js');//測試的文件路徑
mocha.run(function(){
    console.log("done");
    process.exit();
})複製代碼

建立文件夾service並在裏面建立app.js、router.spec.js

app.js 啓動一個服務器監聽3000端口,若訪問http://127.0.0.1:3000/test便返回數據data

var express = require('express');
var app = express();

app.get('/test', function (req, res) {
    res.send({
        data:'Hello World'
    });
});

var server = app.listen(3000, function () {
    console.log('服務啓動');
});
module.exports = app;複製代碼

要安裝express

npm install express複製代碼

router.spec.js

const axios = require('axios');
const { expect } = require('chai');
describe("node接口測試",function(){
    it("test 接口測試",(done) => {
        axios.get('http://localhost:3000/test') //請求的url
            .then(function (res) {
            expect(res.status).to.equal(200);
            console.log(res.data)
            if(res.data.data == "Hello World!"){
                    done();
            }else{
                    done(new Error('結果不符合預期!!!'));
            }
            }).catch(function (error) {
            done(error);
        });
    });
});複製代碼

須要安裝axios

npm install axios複製代碼

啓動mocha

mocha ./mochaRunner.js複製代碼

或者

node ./mochaRunner.js複製代碼


將會在同級目錄生成mochawesome-reports,訪問html


也能夠在package.json中配置:

"scripts": {
  "test": "npm run unit",
  "e2e": "node ./e2e/baidu.js",
  "unit": "karma start",
  "uitest": "backstop test",
  "service": "mocha ./mochaRunner.js"
},複製代碼

這樣就能夠直接使用npm run ***

結尾:

前端自動化測試的框架還有不少不少,例如:Rizejs、Nightwhatchjs、F2etest等等。剛接觸這些測試框架,有太多的不懂,這就須要時間的積累,不斷學習,不斷進步,讓本身成長爲想要成爲的那個本身,感謝你們觀看!!!

相關文章
相關標籤/搜索