介绍
karma是google团队开发并使用的一款测试工具,可以直接在编译器上模拟真实的浏览器环境测试你的代码可用性,节约软件工程师的测试时间,让生活变得更美好。
karma的原名叫做Testacular,官网(http://karma-runner.github.io/)
运行环境
node.js => v10.15.3
npm => 6.9.0
npm升级到最新版本,请在终端执行如下命令:
npm install -g npm
安装
创建项目目录karma-test,项目内新建一个test的文件夹,test文件夹下新建一个空的test.js文件。返回到项目根目录,执行:
npm init
一路回车,完成项目的初始化工作。
安装karma和karma-cli包文件
npm install -g karma
npm install karma --save-dev
npm install karma-cli --save-dev
打开vs code 编译器,选择karma-test项目。
运行
执行以下命令
karma start
成功运行后会在终端看到这几行代码
18 03 2019 13:28:41.718:WARN [karma]: No captured browser, open http://localhost:9876/
18 03 2019 13:28:42.104:INFO [karma-server]: Karma v4.0.1 server started at http://0.0.0.0:9876/
18 03 2019 13:28:42.106:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
18 03 2019 13:28:42.158:INFO [launcher]: Starting browser Chrome
18 03 2019 13:28:44.603:INFO [Chrome 72.0.3626 (Windows 10.0.0)]: Connected on socket 7_sdaXFbt_iYPh_oAAAA with id 15439757
打开生成的地址,如上图 http://localhost:9876/,开启的页面效果如下图:
当前我们建的项目内test.js文件是空的,虽然运行正常,但是缺少测试方法,所以终端返回给我们这样一段话:
Chrome 72.0.3626 (Windows 10.0.0) ERROR
{
"message": "You need to include some adapter that implements __karma__.start method!",
"str": "You need to include some adapter that implements __karma__.start method!"
}
You need to include ... method!看来是少了点什么,需要对karma做些配置,并且在test.js文件中写入测试用例(这是重点)。
配置
- karma初始化
karma init
初始化会问你一堆问题,整理如下
- Which testing framework do you want to use ? => mocha
- Do you want to use Require.js ? => no
- Do you want to capture any browsers automatically ? => Chrome
- What is the location of your source and test files ? => test/**.js
- Should any of the files included by the previous patterns be excluded ? => 直接回车
- Do you want Karma to watch all the files and run the tests on change ? => yes
完成后生成一个karma.conf.js的文件。
示例
我们来复制如下代码到test.js:
describe('jQuery', function () {
it('should have jQuery', function () {
if (!window.jQuery) {
throw new Error('查看下 karma.conf.js 配置项 files 是否正确')
}
});
});
以上是一段检查浏览器是否支持jQuery插件的测试用例,运行命令:
karma start
终端显示返回如下:
18 03 2019 13:25:00.012:INFO [filelist]: Changed file "F:/learning/karma-test/test/test.js".
Chrome 72.0.3626 (Windows 10.0.0) jQuery should have jQuery FAILED
Error: 查看下 karma.conf.js 配置项 files 是否正确
at Context.<anonymous> (test/test.js:4:13)
Chrome 72.0.3626 (Windows 10.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.007 secs / 0 secs)
karma检测当前chrome浏览器不支持jQuery,抛了个错误信息。
那如果是测试正常返回什么信息呢?我们修改下test.js:
describe('true test', function () {
it('contains a passing spec', function () {
console.log('Hello Karma');
})
});
终端打印的信息:
18 03 2019 14:16:02.485:INFO [filelist]: Changed file "F:/learning/karma-test/test/test.js".
LOG: 'Hello Karma'
Chrome 72.0.3626 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.005 secs / 0 secs)
TOTAL: 1 SUCCESS
1 SUCCESS
教程到此结束!