FED

©FrontEndDev.org
2015 - 2024
web@2.22.0 api@2.20.0

webstorm入门4-karma/jasmine/coverage/coveralls/phantomjs/travis-ci单元测试

img.png

build success、coverage 100% 是否让你羡慕不已?作为程序员不要再 low 了,开始启动单元测试吧。

名词解释

文章标题陈列了一共7个英文单词。除了 webstorm 是在之前的文章已经介绍过的,下面分别介绍下其他几个单词:

karma

karma 的中文意思是“因果报应”。

官网:http://karma-runner.github.io/0.12/index.html,维护组织是谷歌。

在2012年google开源了Testacular,2013年Testacular改名为Karma。Karma是一个让人感到非常神秘的名字,表示佛教中的缘分,因果报应,比Cassandra这种名字更让人猜不透!

Karma是一个基于Node.js的JavaScript测试执行过程管理工具(Test Runner)。该工具可用于测试所有主流Web浏览器以及 PhantomJS,也可集成到CI(Continuous integration)工具。

Things should be simple. We believe in testing and so we want to make it as simple as possible.

The main goal for Karma is to bring a productive testing environment to developers. The environment being one where they don't have to set up loads of configurations, but rather a place where developers can just write the code and get instant feedback from their tests. Because getting quick feedback is what makes you productive and creative.

以上是官网对她的定义。

简而言之,karma 的出现减轻了前端开发的测试难度,一切自动化,尤其是搭配 webstorm 之后,方便程度不可名状。

jasmine

jasmine 的中文意思是“茉莉花”。

官网:http://jasmine.github.io/,维护组织是谷歌。

Behavior-Driven JavaScript Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests. This guide is running against Jasmine version 2.0.0.

jasmine 是行为驱动的单元测试工具。

coverage

中文意思是“覆盖率”。

官网:https://github.com/karma-runner/karma-coverage

本文要介绍的单元测试覆盖率实现工具是 istanbul,她被内置在 karma-coverage 模块(后文详细介绍)中。

coveralls

是覆盖率的变身。

官网:https://coveralls.io/

是描述 github 上项目的覆盖率的第三方工具。在开篇的图示中,“coverage 100%”就是由她提供的。

phantomjs

phantom 的中文意思是“幻象”。

PhantomJS 是一个基于 WebKit 的服务器端 JavaScript API,它基于 BSD 开源协议发布。PhantomJS 无需浏览器的支持即可实现对 Web 的支持,且原生支持各种 Web 标准,如 DOM 处理、JavaScript、CSS 选择器、JSON、Canvas和可缩放矢量图形SVG。PhantomJS 主要是通过 JavaScript 和CoffeeScript 控制 WebKit 的 CSS 选择器、可缩放矢量图形 SVG 和 HTTP 网络等各个模块。

PhantomJS 实现的是无图形界面的浏览器。在此,他于在前端测试的时候,以不必打开浏览器就可以完成测试。比如,生成长微博等服务就可以用 phantomJS 实现。

travis-ci

代码测试跟踪服务,用于在线测试你提交的代码,如开篇图中的“passing”图标。

官网:https://travis-ci.org/

单元测试步骤

安装必要模块

  • karma:跑单元测试的框架。类似于 grunt、gulp。
  • karma-jasmine:跑单元测试的工具。同类的还有 mocha。
  • karma-coverage:单元测试覆盖率计算工具。
  • karma-coveralls:将单元测试结果推送到 coveralls.io。
  • karma-phantomjs-launcher:phantomJS 启动工具。同类还有 chrome、ie、firefox 启动工具。

执行

npm i -SD karma karma karma-jasmine karma-coverage karma-coveralls karma-phantom-launcher

安装。

注册必要账号

在安装必要模块的同时,可以先注册或添加 repository 到:

单元测试在线服务

官网:https://travis-ci.org/

img.png

在项目根目录新建.travis.yml文件,文件内容为:

language: node_js
node_js:
  - 0.10
before_script:
  - export DISPLAY=:99.0
  - sh -e /etc/init.d/xvfb start
script:
  - npm test

单元测试命令只需要写在 package.json 的 scripts 里即可。

单元测试覆盖率结果服务

官网:https://coveralls.io/

授权登录后,添加 github 项目即可,后续操作都是自动化的。此时可以在 coveralls.io 上看到以下信息:

img.png

将以上代码复制下来,然后在项目根目录新建.coveralls.yml文件。注意,需要将此文件添加到.gitignore里,防止被提交到 github 上去。

初始化测试文件

可以执行

node node_modules/karma/bin/karma init

来自动生成,也可以参考下述文件,及注释内容:

// Karma configuration
// Generated on Fri Apr 24 2015 14:29:09 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
		// 测试工具,可选 jasmine、mocha 等
        frameworks: ['jasmine'],


		// 客户端配置,比如浏览器的 UI、是否隐身模式等,不推荐修改
        client: {},


        // list of files / patterns to load in the browser
		// 被浏览器加载和可访问的文件列表
        files: [
			// 直接在页面上加载的文件
            './examples/coolie.min.js',
            {
                pattern: './src/**/*',
				// 不会直接在页面上加载的文件,但可以使用 URL 来访问,通常是用于异步加载的模块文件
                included: false
            },
			// 测试文件,必填
            './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: {
            './src/**/*.js': ['coverage']
        },


        // optionally, configure the reporter
		// 代码覆盖率报告,不推荐修改
        coverageReporter: {
            type: 'lcov',
            dir: './coverage/'
        },


        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
		// 测试报告,不推荐修改
        reporters: ['progress', '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
		// 是否监听测试文件,自动执行测试,不推荐修改,可在 webstorm 里配置
        autoWatch: false,


        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		// 启动的浏览器,不推荐修改,可在 webstorm 里配置
        browsers: [],


        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
		// 单独模式,为 true 即只跑完测试之后退出,不推荐修改
        singleRun: true,


        // plugins
		// 加载的插件,不推荐修改
        plugins: ['karma-*']
    });
};

配置 webstorm karma

img.png

保存之后:

img.png

第一个图标为:单元测试,第三个图标为:覆盖率测试。

点击单元测试后:

img.png

首次会提示你打开浏览器,测试完毕后:

img.png

也可以修改浏览器为 phantomJS:

img.png

打开 webstorm 控制台:

img.png

显示的有当前的测试用例和相关按钮。webstorm 执行单元覆盖率测试同理。图示单元测试覆盖率报告:

img.png

代码的单元测试覆盖率示意图:

img.png

提交在线单元测试

只需要 push 到 github 上即可,github 会通知 travis-ci.org 执行单元测试。

提交覆盖率报告

webstorm 配置如图:

img.png

保存后,启动图标

img.png

此时,模块的单元测试覆盖率已提交至 coveralls.io。