3. Karma + Jasmine配置
初始化karma配置文件karma.conf.js
~ D:\workspace\javascript\karma>karma 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 > 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. > 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 "D:\workspace\javascript\karma\karma.conf.js". |
安装集成包karma-jasmine
~ D:\workspace\javascript\karma>npm install karma-jasmine
4. 自动化单元测试
3步准备工作:
1. 创建源文件:用于实现某种业务逻辑的文件,就是我们平时写的js脚本
2. 创建测试文件:符合jasmineAPI的测试js脚本
3. 修改karma.conf.js配置文件
1). 创建源文件:用于实现某种业务逻辑的文件,就是我们平时写的js脚本
有一个需求,要实现单词倒写的功能。如:”ABCD” ==> “DCBA”
~ vi src.js function reverse(name){ return name.split("").reverse().join(""); } |
2). 创建测试文件:符合jasmineAPI的测试js脚本
describe("A suite of basic functions", function() { it("reverse word",function(){ expect("DCBA").toEqual(reverse("ABCD")); }); }); |
3). 修改karma.conf.js配置文件
我们这里需要修改:files和exclude变量
module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine'], files: ['*.js'], exclude: ['karma.conf.js'], reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], captureTimeout: 60000, singleRun: false }); }; |
启动karma
单元测试全自动执行
~ D:\workspace\javascript\karma>karma start karma.conf.js INFO [karma]: Karma v0.10.2 server started at http://localhost:9876/ INFO [launcher]: Starting browser Chrome WARN [launcher]: The path should not be quoted. Normalized the path to C:\Program Files (x86)\Google\Chrome\Application\chrome.exe INFO [Chrome 28.0.1500 (Windows 7)]: Connected on socket bVGffDWpc1c7QNdYye_6 INFO [Chrome 28.0.1500 (Windows 7)]: Connected on socket DtTdVbd4ZsgnMQrgye_7 Chrome 28.0.1500 (Windows 7): Executed 1 of 1 SUCCESS (3.473 secs / 0.431 secs) Chrome 28.0.1500 (Windows 7): Executed 1 of 1 SUCCESS (0.068 secs / 0.021 secs) TOTAL: 2 SUCCESS |
浏览器会自动打开