codecamp

Introduction to automated testing

先决条件: 熟悉核心 HTML CSS JavaScript 语言; 高级跨浏览器测试原则的概念。
目的: 提供对自动化测试所需的理解,如何使您的生活更轻松,以及如何利用一些使事情更容易的商业产品。

自动化使事情变得容易

在本单元中,我们详细介绍了各种不同的测试网站和应用程序的方式,并解释了跨浏览器测试工作在测试浏览器,辅助功能考虑等方面的范围。 听起来像很多工作,不是吗?

我们同意 - 测试我们在以前的文章中看过的所有东西可能是一个真正的痛苦。 幸运的是有工具来帮助我们自动化这些痛苦。 有两个主要方法,我们可以自动化这个模块中我们一直在谈论的测试:

  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.

我们将在下一篇文章中讨论如何设置自己的基于Selenium的测试系统。 在本文中,我们将讨论如何设置任务运行器,并使用上面提到的商业系统的基本功能。

注意:上述两个类别不是互斥的。 可以通过API设置任务运行器以访问Sauce Labs等服务,运行跨浏览器测试并返回结果。 我们将在下面看看。

使用任务运行器自动化测试工具

如上所述,您可以通过使用任务运行器来运行您在构建过程中的某个时间点自动运行的所有内容,从而大大加快常见任务(例如,删除和缩小代码)。 例如,这可以是每次您保存文件,或在某个其他点。 在本节中,我们将介绍如何使用Node和Gulp自动执行任务运行,这是一个初学者友好的选项。

设置节点和npm

目前大多数这样的工具都基于Node.js(一个服务器端JavaScript环境,允许您构建服务器端Web应用程序,自动执行任务等),因此您需要从 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

注意:如果上述命令失败并出现权限错误,请修复 npm权限应该排除你。

要开始在项目中使用基于节点/ npm的包,您需要将项目目录设置为npm项目。 这很容易做到。

例如,让我们首先创建一个测试目录,让我们在不害怕打破任何东西的情况下玩。

  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.

这个文件基本上是一个项目的配置文件。 您可以稍后自定义,但现在它看起来像这样:

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

有了这个,你准备继续前进。

设置Gulp自动化

让我们来看看设置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添加一些真正的任务

要向Gulp添加一些真正的任务,我们需要考虑我们想要做什么。 在我们的项目上运行的一组合理的基本功能如下:

  • 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).

有关我们使用的不同gulp软件包的完整说明,请参阅上面的链接。

要使用每个插件,你需要首先通过npm安装,然后在 gulpfile.js 文件的顶部要求任何依赖项,然后将测试添加到它的底部,最后 请在默认任务中添加任务名称。

在进一步操作之前,将默认任务更新为:

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

当你在命令行中运行 gulp 命令时,数组中的所有任务的名称都将被Gulp运行。

html-tidy

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

    注意: - save-dev 将软件包作为依赖项添加到项目中。 如果你查看你的项目的 package.json 文件,你会看到一个条目已经添加到 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.

这里我们正在抓住我们的开发 index.html 文件 - gulp.src()允许我们抓取源文件来做某事。

我们接下来使用 pipe()函数将该源传递给另一个执行别的操作的命令。 我们可以连接许多这些在一起,因为我们想要的。 我们首先在源代码上运行 htmltidy(),它会找到并修复我们文件中的错误。 第二个 pipe()函数将输出HTML文件写入 build 目录。

在文件的输入版本中,您可能已经注意到我们将空的 < p> 元素; htmltidy在创建输出文件的时候删除了这个。

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输出到构建目录。 注意,这只有当csslint没有找到任何错误 - 只是尝试从CSS文件中删除大括号和重新运行gulp看到你得到什么输出!

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,将其转换为旧样式语法,并将结果输出到 build 目录中。 我们的原始代码包括胖箭功能,其中babel已修改为 一个旧样式函数。

Further ideas

一旦所有这些都设置完成,您可以在项目目录中运行 gulp 命令,您应该得到如下所示的输出:

>

然后,您可以通过查看 build 目录中的文件并在Web浏览器中加载 build / index.html ,来尝试自动化任务输出的文件。

如果您收到错误,请检查您是否已添加所有依赖项和测试,如上所示; 也尝试注释掉HTML / CSS / JavaScript代码部分,然后重新运行gulp,看看是否可以隔离问题是什么。

Gulp附带了一个 watch()函数,可以用来在保存文件时观察文件并运行测试。 例如,尝试将以下内容添加到 gulpfile.js 的底部:

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

现在尝试输入 gulp watch 命令到您的终端。 Gulp现在将监视您的目录,并在您将更改保存到HTML,CSS或JavaScript文件时运行相应的任务。

注意: * 字符是一个通配符 - 这里我们说的是"保存这些类型的任何文件时运行这些任务。 任务,例如 gulp.src(\'src / *。css\')将抓取所有的CSS文件,然后在它们上运行管道任务。

注意:上面的watch命令的一个问题是,当遇到CSS错误时,我们的CSSLint / Autoprefixer组合会抛出完整的错误,从而导致手表停止工作。 一旦遇到CSS错误,您必须重新启动手表,或者找到其他方法。

有很多你可以做的Gulp。 Gulp插件目录有数千个插件可供搜索。

其他任务跑步者

还有许多其他任务运行器可用。 我们当然不是说Gulp是最好的解决方案,但它适用于我们,它是初学者公平可及。 您也可以尝试使用其他解决方案:

  • 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个浏览器/操作系统组合上免费测试Firefox上的代码

还有其他商业浏览器测试系统可用,但在本文中,我们将专注于Sauce实验室。 我们不是说这是必要的最好的工具,但它是一个很好的初学者起来和运行。

这种应用程序的基本前提是运行每个应用程序的公司有一个巨大的服务器场,可以运行许多不同的测试。 使用此服务时,您需要提供要测试的网页的网址,以及您希望测试的浏览器等信息。应用程序然后使用您指定的操作系统和浏览器配置新的VM,并返回测试 导致截图,视频,日志文件,文本等形式。

然后,您可以升级齿轮,使用API以编程方式访问功能,这意味着此类应用程序可以与任务运行器,您自己的本地Selenium环境等组合,以创建自动测试。

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实验室信息中心提供了很多选项。 现在,请确保您位于手动测试标签上。

  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.

停止会话后,您将返回到手动测试选项卡,在该选项卡中,您将看到您开始的每个以前的手动会话的条目。 单击其中一个条目可显示该会话的更多数据。 在这里,您可以下载您拍摄的任何屏幕截图,观看会话的视频,以及查看会话的数据日志。

注意:这已经非常有用,方式比自己设置所有这些模拟器和虚拟机更方便。

高级:The Sauce Labs API

Sauce实验室具有 Restful API ,可让您以编程方式 检索您的帐户和现有测试的详细信息,并用进一步的详细信息注释测试,例如它们的通过/失败状态,这些不能通过手动测试单独记录。 例如,您可能希望使用Sauce Labs远程运行您自己的Selenium测试,测试某个浏览器/操作系统组合,然后将测试结果传回Sauce Labs。

它有一些客户端可用于允许您使用您最喜欢的环境(无论是PHP,Java,Node.js等)调用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设置自己的本地自动化系统,以及如何与Sauce Labs结合使用。

Implementing feature detection
Setting up your own test automation environment
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录
CSS

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }