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

eternalless發表於2018-06-03

前言:

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

github地址:fetest

1.Karma+Jasmine+karma-coverage

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

Karma是一個基於Node.js的JavaScript測試執行過程管理工具( Test Runner ).。該工具可用於測試所有主流Web瀏覽器, 也可整合到CI ( Continuous integration ) 工具, 也可和其他程式碼編輯器一起使用.。這個測試工具的一個強大特性就是, 它可以監控(Watch)檔案的變化, 然後自行執行。

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

1.1 使用 Karma 對程式碼進行單元測試,首先需要安裝一系列的相關外掛。

建立fetest的資料夾,並進入

安裝karma

npm install -g karma-cli複製程式碼
npm install karma --save-dev複製程式碼

安裝各種相關的外掛

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

初始化,整體的配置選項如下:

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複製程式碼

啟動karma

karma start複製程式碼

出現一下介面代表成功,可進行下一步操作,第一次需要安裝phantomjs

npm install -g phantomjs複製程式碼

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

初始化完成之後,會在我們的專案中生成一個 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複製程式碼

入門:前端自動化測試karma,Backstopjs,Selenium-webdriver,Mocha成功了一個,錯誤一個。

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頁面。

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

開啟index.html

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

修改index.spec.js

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

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

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 複製程式碼

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

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

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

再次啟動

backstop test 複製程式碼

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

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)

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

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

建立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複製程式碼

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

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

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

也可以在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等等。剛接觸這些測試框架,有太多的不懂,這就需要時間的積累,不斷學習,不斷進步,讓自己成長為想要成為的那個自己,感謝大家觀看!!!


相關文章