Karma-jasmine前端测试工具的配置(windows环境下)

来源:互联网 发布:mac如何设置手机铃声 编辑:程序博客网 时间:2024/06/08 05:13

注意:本文中出现的资料链接、karma的插件安装等,均可能需要翻$墙后才能正确执行。

 

Jasmine是一个Javascript的测试工具,在Karma上运行Jasmine可完成Javascript的自动化测试、生成覆盖率报告等。本文不包含Jasmine的使用细节,这几天我会写一篇Jasmine的入门文章,有兴趣的朋友到时候可以看一下。

 

步骤一:安装Node.JS(版本:v0.12.4, windows-64)

Karma是运行在Node.js之上的,因此我们首先要安装Node.js。到 https://nodejs.org/download/ 下载你系统所需的NodeJS版本,我下载的是windows-64位的msi版。

下载之后,双击 node-v0.12.4-x64.msi 运行并安装,这个就不赘述了, 不断下一步即可, 当然最好将目录改一下。

图1(选择安装内容,默认即可):

 

 

步骤二:安装Karma

运行Node.js的命令行程序:Node.js command prompt:

图2(处于“开始->所有程序->Node.js”中):

 

图3(我们将安装到E:\Karma路径下):

 

输入命令安装Karma:

npm install karma --save-dev

 

图4(Karma安装完毕后):

 

步骤三:安装karma-jasmine/karma-chrome-launcher插件

继续输入npm命令安装karma-jasmine、karma-chrome-launcher插件:

npm install karma-jasmine karma-chrome-launcher --save-dev

 

图5(karma-jasmine、karma-chrome-launcher安装完毕之后):

 

步骤四:安装karma-cli

karma-cli用来简化karma的调用,安装命令如下,其中-g表示全局参数,这样今后可以非常方便的使用karma了:

npm install -g karma-cli

 

图6(karma-cli安装完毕之后):

 

Karma-Jasmine安装完毕:

图7(安装完毕后,在E:\Karma文件夹下会有一个node_modules目录,里面包含刚才安装的karma、karma-jasmine、karma-chrome-launcher目录,当然还包含了jasmine-core目录):

 

开启Karma:

输入命令:

karma start

 

图8(运行后如图所示出现了一行INFO信息,并没有其他提示和动作,因为此时我们没有配置karma的启动参数。后面会加入karma.conf.js,这样karma就会自动启动浏览器并执行测试用例了):

 

图9(手动打开Chrome,输入localhost:9876,如果看到这个页面,证明已经安装成功):

 

Karma+Jasmine配置:

执行命令init命令进行配置:

karma init

 

图10(所有默认配置问题):

 

 说明:

1. 测试框架:我们当然选jasmine

2. 是否添加Require.js插件

3. 选择浏览器: 我们选Chrome

4. 测试文件路径设置,文件可以使用通配符匹配,比如*.js匹配指定目录下所有的js文件(实际操作中发现该路径是karma.conf.js文件的相对路径,详见下面我给出的实际测试配置及说明)

5. 在测试文件路径下,需要排除的文件

6. 是否允许Karma监测文件,yes表示当测试路径下的文件变化时,Karma会自动测试

 

我在虚拟机上测试的例子:

图11(TestFiles和NodeJS处于E盘根目录下,karma.conf.js处于文件夹NodeJS的根目录下):

 

以下是karma.conf.js的完整内容:

复制代码
 1 // Karma configuration 2 // Generated on Fri May 29 2015 19:30:26 GMT+0800 (中国标准时间) 3  4 module.exports = function(config) { 5   config.set({ 6  7     // base path that will be used to resolve all patterns (eg. files, exclude) 8     basePath: '../TestFiles', 9 10 11     // frameworks to use12     // available frameworks: https://npmjs.org/browse/keyword/karma-adapter13     frameworks: ['jasmine'],14 15 16     // list of files / patterns to load in the browser17     files: [18       '*.js'19     ],20 21 22     // list of files to exclude23     exclude: [24     ],25 26 27     // preprocess matching files before serving them to the browser28     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor29     preprocessors: {30     },31 32 33     // test results reporter to use34     // possible values: 'dots', 'progress'35     // available reporters: https://npmjs.org/browse/keyword/karma-reporter36     reporters: ['progress'],37 38 39     // web server port40     port: 9876,41 42 43     // enable / disable colors in the output (reporters and logs)44     colors: true,45 46 47     // level of logging48     // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG49     logLevel: config.LOG_INFO,50 51 52     // enable / disable watching file and executing tests whenever any file changes53     autoWatch: true,54 55 56     // start these browsers57     // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher58     browsers: ['Chrome'],59 60 61     // Continuous Integration mode62     // if true, Karma captures browsers, runs the tests and exits63     singleRun: false64   });65 };
复制代码

 

说明:

若所有测试文件均处于同一个目录下,我们可以设置basePath(也是相对于karma.conf.js文件的相对路径),然后指定files,此时files则为basePath目录下的文件相对路径;

当然你也可以不设置basePath,直接使用相对于karma.conf.js文件的文件相对路径,如本例中,我们若保持basePath默认为空,则files配置应为:

files: [      '../TestFiles/jasmineTest.js',      '../TestFiles/test.js'    ]

 

test.js内容:

function TT() {    return "abc";}

 

jasmineTest.js内容:

describe("A suite of basic functions", function () {    it("test", function () {        expect("abc").toEqual(TT());    });});

 

启动Karma:

karma start karma.conf.js

由于这次加上了配置文件karma.conf.js,因此Karma会按照配置文件中指定的参数执行操作了,由于我们配置的是在Chrome中测试,因此Karma会自动启动Chrome实例,并运行测试用例:

注意:在启动Karma后可能会报错 :

module.js:340 throw err; ^ Error: Cannot find module 'jasmine-core' at Function.Module._resolveFilename (module.js:338:15) at Function.require.resolve (module.js:384:19) at initJasmine (/usr/lib/node_modules/karma-jasmine/lib/index.js:8:42) at Array.invoke [as 0] (/usr/lib/node_modules/karma/node_modules/di/lib/injector.js:75:15) at get (/usr/lib/node_modules/karma/node_modules/di/lib/injector.js:48:43) at /usr/lib/node_modules/karma/lib/server.js:137:20 at Array.forEach (native) at Server._start (/usr/lib/node_modules/karma/lib/server.js:136:21) at invoke (/usr/lib/node_modules/karma/node_modules/di/lib/injector.js:75:15) at Server.start (/usr/lib/node_modules/karma/lib/server.js:101:18) at Object.exports.run (/usr/lib/node_modules/karma/lib/cli.js:231:26) at Object. (/usr/lib/node_modules/karma/bin/karma:3:23) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12)

说明没有安装jasmine-core插件,安装后即可解决:npm install jasmine-core --save-dev


图12(左侧的Chrome是Karma自动启动的,右侧的Node.js command prompt窗口中,最后一行显示了执行结果):

 

图13(如果我们点击图12中的debug按钮,进入debug.html并按F12打开开发者工具,选择Console窗口,我们将能看到jasmine的执行日志):

 

若此时,我们将jasmineTest.js中对于调用TT方法的期望值改为"abcd"(实际为"abc"):

describe("A suite of basic functions", function () {    it("test", function () {        expect("abcd").toEqual(TT());    });});

 

由于我们在karma.conf.js中设置了autoWatch为true:

autoWatch: true

 

Karma将自动执行测试用例,由于本例测试用例未通过,因此在屏幕上打印出了错误信息,Chrome的Console窗口中的日志信息需要刷新debug.html后显示。

图14(Karma自动检测到文件变化并自动重新执行了测试用例):

 

代码覆盖率:

如果你还想查看测试的代码覆盖率,我们可以安装karma-coverage插件,安装命令为:

npm install karma-coverage

 

图15(安装karma-coverage的过程):

 

修改karma.conf.js,增加覆盖率的配置:

图16(主要是变动了以下三个配置节点,其他的配置内容不变):

复制代码
 1     // preprocess matching files before serving them to the browser 2     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor 3     preprocessors: { 4         '../TestFiles/test.js':'coverage' 5     }, 6  7  8     // test results reporter to use 9     // possible values: 'dots', 'progress'10     // available reporters: https://npmjs.org/browse/keyword/karma-reporter11     reporters: ['progress','coverage'],12     13     coverageReporter:{14         type:'html',15         dir:'../TestFiles/coverage/'16     },
复制代码

 

变动如下:

  • 在reporters中增加coverage
  • preprocessors中指定js文件
  • 添加coverageReporter节点,将覆盖率报告类型type设置为html,输入目录dir指定到你希望的目录中

 

此时完整的karma.conf.js如下:

复制代码
 1 // Karma configuration 2 // Generated on Fri May 29 2015 19:30:26 GMT+0800 (中国标准时间) 3  4 module.exports = function(config) { 5   config.set({ 6  7     // base path that will be used to resolve all patterns (eg. files, exclude) 8     basePath: '', 9 10 11     // frameworks to use12     // available frameworks: https://npmjs.org/browse/keyword/karma-adapter13     frameworks: ['jasmine'],14 15 16     // list of files / patterns to load in the browser17     files: [18       '../TestFiles/jasmineTest.js',19       '../TestFiles/test.js'20     ],21 22 23     // list of files to exclude24     exclude: [25     ],26 27 28     // preprocess matching files before serving them to the browser29     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor30     preprocessors: {31         '../TestFiles/test.js':'coverage'32     },33 34 35     // test results reporter to use36     // possible values: 'dots', 'progress'37     // available reporters: https://npmjs.org/browse/keyword/karma-reporter38     reporters: ['progress','coverage'],39     40     coverageReporter:{41         type:'html',42         dir:'../TestFiles/coverage/'43     },44 45 46     // web server port47     port: 9876,48 49 50     // enable / disable colors in the output (reporters and logs)51     colors: true,52 53 54     // level of logging55     // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG56     logLevel: config.LOG_INFO,57 58 59     // enable / disable watching file and executing tests whenever any file changes60     autoWatch: true,61 62 63     // start these browsers64     // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher65     browsers: ['Chrome'],66 67 68     // Continuous Integration mode69     // if true, Karma captures browsers, runs the tests and exits70     singleRun: false71   });72 };
复制代码

 

执行命令:

karma start karma.conf.js

 

图17(执行命令后,在配置文件coverageReporter节点中指定的dir中,我们将找到生成的覆盖率报告,karma-coverage还生成了一层子文件夹,对应于执行测试的浏览器+版本号+操作系统版本):