在开发软件的过程中,进行单元测试是非常不错的工作,也是有必要的工作。它帮助你觉得你的代码是无懈可击的,确保产品的可靠性。作为一名追求进步的的前端码农,学习前端的测试很有必要。
###Karma简介
Karma是由Angular团队创造的JavaScript测试运行器,实际上,它更是一个测试环境,它让你更方便的运行测试,在不知不觉中监听着源码或者测试代码的改变,然后自动执行测试。
在前端测试上,传统时代的测试方法是在js脚本中写上几个console
或者alert
语句,然后刷新浏览器,查看打印或者弹出的信息。再后来,有了火狐的firebug和Chrome DevTools,js的测试进入了打断点的时代。然而,使用Chrome DevTools也是需要刷新浏览器,然后手动的点击跳步等操作。以上两个时代,前端的测试预期说是测试,不如说是调试,因为此时的测试是代码混着调试语句,在网页应用中(浏览器上)运行。Karma改变了前端测试的工作流程,它让开发者在开发过程中只需关注编写测试用例,编写实现方法等,而无需花费太多精力在无关代码的工作上。
###Karma安装
Karma运行在Node.js上,你可以从NPM包里面获取到。
假设你已经安装了Node.js,按照官方推荐的方法,你可以如下安装Karma以及相关的插件:
# Install Karma:
$ npm install karma --save-dev
# Install plugins that your project needs:
$ npm install karma-jasmine karma-chrome-launcher --save-dev
以上命令将会在你的当前目录下的node_modules
下安装karma
、karma-jasmine
、karma-chrome-launcher
。并且将开发依赖包保存进package.json,方便项目的其他开发人员只需在该目录下运行npm install
就能够安装所有的开发依赖包。
# Run Karma:
$ ./node_modules/karma/bin/karma start
以上的命令是运行Karma,但是每次都打这么长的命令很费劲啊,所以,你可以如下安装karma-cli
,并配置到全局中:
$ npm install -g karma-cli
成功之后,只需运行karma start
就能启动Karma测试了。
###Karma配置
但是启动之前有个很重要的步骤--配置Karma的测试环境。运行karma init
可以生成配置文件:
$ karma init my.conf.js
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 a browser automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
> Safari
>
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.
> *.js
> test/*Spec.js
>
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.
> yes
Config file generated at "/path/to/your/project/my.conf.js".
配置文件的详细语法和选项说明请参考Karma官网的configuration file docs。
###Karma运行
当启动Karma的时候,配置文件的路径会作为第一个参数传递过去。默认地,Karma会在当前目录下查找karma.conf.js
或者karma.conf.coffee
。但是你也可以指定配置文件启动Karma,例如,启动上一步骤生成的my.conf.js
配置文件:
# Start Karma using your configuration:
$ karma start my.conf.js
###第一个测试
在当前目录下创建一个test目录,然后新建一个js文件,命名为testSpec.js
。
|--module
|--test
|--testSpec.js
|--my.conf.js
在testSpec.js
中以下内容:
/**
* Created by ArthurWANG on 14/11/26.
*/
describe('hello world', function () {
it('should contains world', function () {
expect('Hello world').toContain('world');
});
});
上面测试用例用的是Jasmine语法。Jasmine是一个专为JavaScript代码测试的行为驱动开发框架。它不依赖其它的JavaScript框架,不需要DOM。并且它有一个整洁明朗,一目了然的语法,让你能够简单地写测试用例。详细说明与语法介绍请戳此。
打开my.conf.js
,修改files配置如下:
// list of files / patterns to load in the browser
files: [
'test/*Spec.js'
],
启动Karma测试环境:
开启你的Karma测试之旅!
###参考