Introduction to automated testing

2018-05-15 17:26 更新
先決條件: 熟悉核心 HTML , CSS JavaScript 語言; 高級跨瀏覽器測試原則的概念。
目的: 提供對自動化測試所需的理解,如何使您的生活更輕松,以及如何利用一些使事情更容易的商業(yè)產(chǎn)品。

自動化使事情變得容易

在本單元中,我們詳細(xì)介紹了各種不同的測試網(wǎng)站和應(yīng)用程序的方式,并解釋了跨瀏覽器測試工作在測試瀏覽器,輔助功能考慮等方面的范圍。 聽起來像很多工作,不是嗎?

我們同意 - 測試我們在以前的文章中看過的所有東西可能是一個真正的痛苦。 幸運的是有工具來幫助我們自動化這些痛苦。 有兩個主要方法,我們可以自動化這個模塊中我們一直在談?wù)摰臏y試:

  1. Use a task runner such as Grunt or Gulp, or npm scripts to run tests and clean up code during your build process. This is a great way to perform tasks like linting and minifying code, adding in CSS prefixes or transpiling nascent JavaScript features for maximum cross-browser reach, and so on.
  2. Use a browser automation system like Selenium to run specific tests on installed browsers and return results, alerting you to failures in browsers as they crop up. Commercial cross-browser testing apps like Sauce Labs and Browser Stack are based on Selenium, but allow you to access their set up remotely using a simple interface, saving you the hassle of setting up your own testing system.

我們將在下一篇文章中討論如何設(shè)置自己的基于Selenium的測試系統(tǒng)。 在本文中,我們將討論如何設(shè)置任務(wù)運行器,并使用上面提到的商業(yè)系統(tǒng)的基本功能。

注意:上述兩個類別不是互斥的。 可以通過API設(shè)置任務(wù)運行器以訪問Sauce Labs等服務(wù),運行跨瀏覽器測試并返回結(jié)果。 我們將在下面看看。

使用任務(wù)運行器自動化測試工具

如上所述,您可以通過使用任務(wù)運行器來運行您在構(gòu)建過程中的某個時間點自動運行的所有內(nèi)容,從而大大加快常見任務(wù)(例如,刪除和縮小代碼)。 例如,這可以是每次您保存文件,或在某個其他點。 在本節(jié)中,我們將介紹如何使用Node和Gulp自動執(zhí)行任務(wù)運行,這是一個初學(xué)者友好的選項。

設(shè)置節(jié)點和npm

目前大多數(shù)這樣的工具都基于Node.js(一個服務(wù)器端JavaScript環(huán)境,允許您構(gòu)建服務(wù)器端Web應(yīng)用程序,自動執(zhí)行任務(wù)等),因此您需要從 https://nodejs.org/"class ="external"> nodejs.org :

  1. Download the installer for your system from the above site.
  2. Install it like you would any other program. Note that Node comes with Node Package Manager (npm), which allows you to easily install packages, share your own packages with others, and run useful scripts on your projects.
  3. One the install completes, test that node is installed by typing the following in the terminal, which returns the installed versions of Node and npm:
    node -v
    npm -v
  4. If you've got Node/npm already installed, you should update them to their latest versions. To update Node, the most reliable way is to download and install an updated installer package from their website (see link above). To update npm, use the following command in your terminal:
    npm install npm@latest -g

注意:如果上述命令失敗并出現(xiàn)權(quán)限錯誤,請修復(fù) npm權(quán)限應(yīng)該排除你。

要開始在項目中使用基于節(jié)點/ npm的包,您需要將項目目錄設(shè)置為npm項目。 這很容易做到。

例如,讓我們首先創(chuàng)建一個測試目錄,讓我們在不害怕打破任何東西的情況下玩。

  1. Create a new directory somewhere sensible with using your file manager UI, or by navigating to the location you want and running the following command:
    mkdir node-test
  2. To make this directory an npm project, you just need to go inside your test directory and initialize it, with the following:
    cd node-test
    npm init
  3. This second command will ask you a number of questions to find out the information required to set up the project; you can just select the defaults for now.
  4. Once all the questions have been asked, it will ask you if the information entered is OK. type yes and press Enter/Return and npm will generate a package.json file in your directory.

這個文件基本上是一個項目的配置文件。 您可以稍后自定義,但現(xiàn)在它看起來像這樣:

{
  "name": "node-test",
  "version": "1.0.0",
  "description": "Test for npm projects",
  "main": "index.js",
  "scripts": {
    "test": "test"
  },
  "author": "Chris Mills",
  "license": "MIT"
}

有了這個,你準(zhǔn)備繼續(xù)前進(jìn)。

設(shè)置Gulp自動化

讓我們來看看設(shè)置Gulp并使用它來自動化一些測試工具。

  1. To begin with, create a test npm project using the procedure detailed at the bottom of the previous section.
  2. Next, you'll need some sample HTML, CSS and JavaScript content to test your system on — make copies of our sample index.html, main.js, and style.css files in your project folder. You can try your own test content if you like, but bear in mind that such tools won't work on internal JS/CSS — you need external files.
  3. First of all, install gulp globally (meaning, it will be available across all projects) using the following command:
    npm install --global gulp-cli
  4. Next, run the following command inside your npm project directory root to set up gulp as a dependency of your project:
    npm install --save-dev gulp
  5. Now create a new file inside your project directory called gulpfile.js. This is the file that will run all our tasks. Inside the file, put the following:
    var gulp = require('gulp');
    
    gulp.task('default', function() {
      console.log('Gulp running');
    });
    This requires the gulp module we installed earlier, and then runs a basic task that does nothing except for printing a message to the terminal — this in itself is useful for letting us know that Gulp is working. Each gulp task is written in the same basic format — gulp's task() method is run, and given two parameters — the name of the task, and a callback function containing the actual code to run to complete the task.
  6. You can run your gulp task with the following commands — try this now:
    gulp
    

向Gulp添加一些真正的任務(wù)

要向Gulp添加一些真正的任務(wù),我們需要考慮我們想要做什么。 在我們的項目上運行的一組合理的基本功能如下:

  • html-tidy, css-lint, and js-hint to lint and report/fix common HTML/CSS/JS errors (see gulp-htmltidy, gulp-csslint, gulp-jshint).
  • Autoprefixer to scan our CSS and add vendor prefixes only where needed (see gulp-autoprefixer).
  • babel to transpile any new JavaScript syntax features to traditional syntax that works in older browsers (see gulp-babel).

有關(guān)我們使用的不同gulp軟件包的完整說明,請參閱上面的鏈接。

要使用每個插件,你需要首先通過npm安裝,然后在 gulpfile.js 文件的頂部要求任何依賴項,然后將測試添加到它的底部,最后 請在默認(rèn)任務(wù)中添加任務(wù)名稱。

在進(jìn)一步操作之前,將默認(rèn)任務(wù)更新為:

gulp.task('default', [ ]);

當(dāng)你在命令行中運行 gulp 命令時,數(shù)組中的所有任務(wù)的名稱都將被Gulp運行。

html-tidy

  1. Install using the following line:
    npm?install?--save-dev?gulp-htmltidy
    

    注意: - save-dev 將軟件包作為依賴項添加到項目中。 如果你查看你的項目的 package.json 文件,你會看到一個條目已經(jīng)添加到 devDependencies 屬性。

  2. Add the following dependencies to gulpfile.js:
    var htmltidy = require('gulp-htmltidy');
  3. Add the following test to the bottom of gulpfile.js:
    gulp.task('html', function() {
      return gulp.src('src/index.html')
            .pipe(htmltidy())
            .pipe(gulp.dest('build'));
    });
  4. Add 'html' as an item inside the array in the default task.

這里我們正在抓住我們的開發(fā) index.html 文件 - gulp.src()允許我們抓取源文件來做某事。

我們接下來使用 pipe()函數(shù)將該源傳遞給另一個執(zhí)行別的操作的命令。 我們可以連接許多這些在一起,因為我們想要的。 我們首先在源代碼上運行 htmltidy(),它會找到并修復(fù)我們文件中的錯誤。 第二個 pipe()函數(shù)將輸出HTML文件寫入 build 目錄。

在文件的輸入版本中,您可能已經(jīng)注意到我們將空的 < p> 元素; htmltidy在創(chuàng)建輸出文件的時候刪除了這個。

Autoprefixer and css-lint

  1. Install using the following lines:
    npm install --save-dev gulp-autoprefixer
    npm install --save-dev gulp-csslint
  2. Add the following dependencies to gulpfile.js:
    var autoprefixer = require('gulp-autoprefixer');
    var csslint = require('gulp-csslint');
  3. Add the following test to the bottom of gulpfile.js:
    gulp.task('css', function() {
        return gulp.src('src/style.css')
            .pipe(csslint())
            .pipe(csslint.formatter('compact'))
            .pipe(autoprefixer({
                browsers: ['last 5 versions'],
                cascade: false
            }))
            .pipe(gulp.dest('build'));
    });
  4. Add 'css' as an item inside the array in the default task.

在這里,我們抓住我們的 style.css 文件,對它運行csslint(它輸出一個CSS中的任何錯誤的列表到終端),然后通過autoprefixer運行它添加任何前綴, 功能在舊版瀏覽器中運行。 在管道鏈的末尾,我們將修改的前綴CSS輸出到構(gòu)建目錄。 注意,這只有當(dāng)csslint沒有找到任何錯誤 - 只是嘗試從CSS文件中刪除大括號和重新運行g(shù)ulp看到你得到什么輸出!

js-hint and babel

  1. Install using the following lines:
    npm install --save-dev gulp-babel babel-preset-es2015
    npm?install?jshint?gulp-jshint?--save-dev
    
  2. Add the following dependencies to gulpfile.js:
    var babel = require('gulp-babel');
    var?jshint?=?require('gulp-jshint');
    
  3. Add the following test to the bottom of gulpfile.js:
    gulp.task('js', function() {
    ??? return gulp.src('src/main.js')
    ??????? .pipe(jshint())
    ??????? .pipe(jshint.reporter('default'))
    ??????? .pipe(babel({
    ??????????? presets: ['es2015']
    ??????? }))
    ??????? .pipe(gulp.dest('build'));
    });
  4. Add 'js' as an item inside the array in the default task.

這里我們抓住我們的 main.js 文件,運行 jshint 就可以使用 jshint.reporter 然后將文件傳遞給babel,將其轉(zhuǎn)換為舊樣式語法,并將結(jié)果輸出到 build 目錄中。 我們的原始代碼包括胖箭功能,其中babel已修改為 一個舊樣式函數(shù)。

Further ideas

一旦所有這些都設(shè)置完成,您可以在項目目錄中運行 gulp 命令,您應(yīng)該得到如下所示的輸出:

>

然后,您可以通過查看 build 目錄中的文件并在Web瀏覽器中加載 build / index.html ,來嘗試自動化任務(wù)輸出的文件。

如果您收到錯誤,請檢查您是否已添加所有依賴項和測試,如上所示; 也嘗試注釋掉HTML / CSS / JavaScript代碼部分,然后重新運行g(shù)ulp,看看是否可以隔離問題是什么。

Gulp附帶了一個 watch()函數(shù),可以用來在保存文件時觀察文件并運行測試。 例如,嘗試將以下內(nèi)容添加到 gulpfile.js 的底部:

gulp.task('watch', function(){
  gulp.watch('src/*.html', ['html']);
  gulp.watch('src/*.css', ['css']);
  gulp.watch('src/*.js', ['js']);
});

現(xiàn)在嘗試輸入 gulp watch 命令到您的終端。 Gulp現(xiàn)在將監(jiān)視您的目錄,并在您將更改保存到HTML,CSS或JavaScript文件時運行相應(yīng)的任務(wù)。

注意: * 字符是一個通配符 - 這里我們說的是"保存這些類型的任何文件時運行這些任務(wù)。 任務(wù),例如 gulp.src(\'src / *。css\')將抓取所有的CSS文件,然后在它們上運行管道任務(wù)。

注意:上面的watch命令的一個問題是,當(dāng)遇到CSS錯誤時,我們的CSSLint / Autoprefixer組合會拋出完整的錯誤,從而導(dǎo)致手表停止工作。 一旦遇到CSS錯誤,您必須重新啟動手表,或者找到其他方法。

有很多你可以做的Gulp。 Gulp插件目錄有數(shù)千個插件可供搜索。

其他任務(wù)跑步者

還有許多其他任務(wù)運行器可用。 我們當(dāng)然不是說Gulp是最好的解決方案,但它適用于我們,它是初學(xué)者公平可及。 您也可以嘗試使用其他解決方案:

  • Grunt works in a very similar way to Gulp, except that it relies on tasks specified in a config file, rather than written using JavaScript. See Getting started with Grunt for more details.
  • You can also run tasks directly using npm scripts located inside your package.json file, without needing to install any kind of extra task runner system. This works on the premise that things like Gulp plugins are basically wrappers around command line tools. So if you can work out how to run the tools using the command line, you can then run them using npm scripts. It is a bit more tricky to work with, but can be rewarding for those who are strong with their command line skills. Why npm scripts? provides a good introduction with a good deal of further information.

使用Sauce Labs加速瀏覽器測試

在我們的合作伙伴Sauce Labs的超過800個瀏覽器/操作系統(tǒng)組合上免費測試Firefox上的代碼。

還有其他商業(yè)瀏覽器測試系統(tǒng)可用,但在本文中,我們將專注于Sauce實驗室。 我們不是說這是必要的最好的工具,但它是一個很好的初學(xué)者起來和運行。

這種應(yīng)用程序的基本前提是運行每個應(yīng)用程序的公司有一個巨大的服務(wù)器場,可以運行許多不同的測試。 使用此服務(wù)時,您需要提供要測試的網(wǎng)頁的網(wǎng)址,以及您希望測試的瀏覽器等信息。應(yīng)用程序然后使用您指定的操作系統(tǒng)和瀏覽器配置新的VM,并返回測試 導(dǎo)致截圖,視頻,日志文件,文本等形式。

然后,您可以升級齒輪,使用API以編程方式訪問功能,這意味著此類應(yīng)用程序可以與任務(wù)運行器,您自己的本地Selenium環(huán)境等組合,以創(chuàng)建自動測試。

Sauce Labs入門

讓我們開始一個Sauce實驗室試用。

  1. Create a Sauce Labs trial account.
  2. Sign in. This should happen automatically after you verify your e-mail address.

基本:手動測試

Sauce實驗室信息中心提供了很多選項。 現(xiàn)在,請確保您位于手動測試標(biāo)簽上。

  1. Click Start a new manual session.
  2. In the next screen, type in the URL of a page you want to test (use http://mdn.github.io/learning-area/javascript/building-blocks/events/show-video-box-fixed.html, for example), then choose a browser/OS combination you want to test by using the different buttons and lists. There is a lot of choice, as you'll see!
  3. When you click Start session, a loading screen will then appear, which spins up a virtual machine running the combination you chose.
  4. When loading has finished, you can then start to remotely test the web site running in the chosen browser.
  5. From here you can see the layout as it would look in the browser you are testing, move the mouse around and try clicking buttons, etc. The top menu allows you to:
    • Stop the session
    • Give someone else a URL so they can observe the test remotely.
    • Copy text/notes to a remote clipboard.
    • Take a screenshot.
    • Test in full screen mode.

停止會話后,您將返回到手動測試選項卡,在該選項卡中,您將看到您開始的每個以前的手動會話的條目。 單擊其中一個條目可顯示該會話的更多數(shù)據(jù)。 在這里,您可以下載您拍攝的任何屏幕截圖,觀看會話的視頻,以及查看會話的數(shù)據(jù)日志。

注意:這已經(jīng)非常有用,方式比自己設(shè)置所有這些模擬器和虛擬機更方便。

高級:The Sauce Labs API

Sauce實驗室具有 Restful API ,可讓您以編程方式 檢索您的帳戶和現(xiàn)有測試的詳細(xì)信息,并用進(jìn)一步的詳細(xì)信息注釋測試,例如它們的通過/失敗狀態(tài),這些不能通過手動測試單獨記錄。 例如,您可能希望使用Sauce Labs遠(yuǎn)程運行您自己的Selenium測試,測試某個瀏覽器/操作系統(tǒng)組合,然后將測試結(jié)果傳回Sauce Labs。

它有一些客戶端可用于允許您使用您最喜歡的環(huán)境(無論是PHP,Java,Node.js等)調(diào)用API。

讓我們簡要了解如何使用Node.js和 node-saucelabs 訪問API 。

  1. First, set up a new npm project to test this out, as detailed in Setting up Node and npm. Use a different directory name than before, like sauce-test for example.
  2. Install the Node Sauce Labs wrapper using the following command:
    npm install saucelabs
  3. Create a new file inside your project root called call-sauce.js. give it the following contents:
    var SauceLabs = require('saucelabs');
    
    var myAccount = new SauceLabs({
      username: "your-sauce-username",
      password: "your-sauce-api-key"
    });
    
    myAccount.getAccountDetails(function (err, res) {
    ? console.log(res);
      myAccount.getServiceStatus(function (err, res) {
    ?   // Status of the Sauce Labs services
    ?   console.log(res);
    ?   myAccount.getJobs(function (err, jobs) {
    ???   // Get a list of all your jobs
    ???   for (var k in jobs) {
    ?????   if ( jobs.hasOwnProperty( k )) {
    ???????   myAccount.showJob(jobs[k].id, function (err, res) {
    ???????     var str = res.id + ": Status: " + res.status;
    ?????????   if (res.error) {
    ???????????   str += "\033[31m Error: " + res.error + " \033[0m";
    ?????????   }
    ???????     console.log(str);
    ???????   });
    ?????   }
    ???   }
    ?   });
    ? });
    });
  4. You'll need to fill in your Sauce Labs username and API key in the indicated places. These can be retrieved from your User Settings page. Fill these in now.
  5. Make sure everything is saved, and run your file like so:
    node call-sauce

高級:自動測試

我們將在下一篇文章中介紹實際運行的自動化Sauce實驗室測試。

概要

這是一個很好的騎行,但我相信你可以開始看到自動化工具在測試方面為你提供了很多重要的好處。

在下一篇文章中,我們將介紹使用Selenium設(shè)置自己的本地自動化系統(tǒng),以及如何與Sauce Labs結(jié)合使用。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號