测试一般包含几个方面:
- 单元测试
- 功能测试
- 性能测试
- 安全测试
开发人员最常的是单元测试和功能测试。单元测试是对一个独立的模块或功能或函数,进行细粒度的测试。Karma
可用于单元测试,方便地在多平台多浏览器端、无浏览器端等各种场景提供测试。
Karma - Spectacular JavaScript Test Runner
Karma(原名Testaclar)是google开源的基于Nodejs的JavaScript测试运行工具(Test Runner)。
如果有以下场景,可使用Karma
- You want to test code in real browsers.
- You want to test code in multiple browsers (desktop, mobile, tablets, etc.).
- You want to execute your tests locally during development.
- You want to execute your tests on a continuous integration server.
- You want to execute your tests on every save.
- You love your terminal.
- You don't want your (testing) life to suck.
- You want to use Istanbul to automagically generate coverage reports.
- You want to use RequireJS for your source files.
karma
不是关于如何编写测试代码的(这些是测试框架或断言库的工作)。karma
仅启动Http server、生成运行于浏览器进行测试的html file(称为client page)、监测文件变化并通知html file。
具体如何编写测试代码,需要测试框架(testing framework)来完成。常用的测试框架有:Jasmine/, Mocha, QUnit等。 Karma针对每个测试框架都有响应的adapter: karma-jasmine,karma-mocha, karma-qunit
安装和配置
安装karma及相关plugin
# Install Karma:
$ npm install karma --save-dev
# Install plugins that your project needs:
$ npm install karma-jasmine karma-chrome-launcher jasmine-core --save-dev
初始化配置文件
karma init karma.config.js // 初始化配置文件
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 a browser automatically?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
> Firefox
>
What is the location of your source and test files?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Press Enter to move to the next question.
> *.js
> test/**/*.js
>
Should any of the files included by the previous patterns be excluded?
You can use glob patterns, eg. "**/*.swp".
Press Enter 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 "/karma.conf.js".
启动karma
$ karma start karma.config.js
启动后会根据配置文件启动服务server并在目标浏览器里启动测试容器页(client html page):http://localhost:9876
如果浏览器选择ChromeHeadless
,则不会启动浏览器。
要在不同浏览器测试,需要安装对应的launcher插件:
karma-chrome-launcher
karma-firefox-launcher
karma-safari-launcher
工作原理
- 基于配置文件和插件,启动server
- 启动目标浏览器,并打开karam client page。
- server监控测试代码文件变动,并通过socket通知client page
- client page通知context page运行测试代码,收集测试结果,返回给server
- server端的reporter负责处理测试结果:打印到console,保存到文件,发送给其他service等
说明:
- client page包含socket和iframe,分别用于与server通信、运行测试代码
- server和client page之间通过websocket通信, context page与client page通过postMessage通信
- 浏览器里的adapter(karma-jasmine)和server端的reporter,分别用于运行测试和处理测试结果。他们都成对出现,如karma-jasmine
流程图如下:
Client page如下:
网友评论