brew install node
npm i -g karma-clin
npm i --save-dev karma
npm install jasmine-core --save-dev
➜ 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 any browsers 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.
> src/*.js
> test/*.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 "/Users/janehai/Documents/karma/karma.conf.js".
karma-example
├── src
├── index.js
├── test
├── test.js
function isNum(num) {
if (typeof num === 'number') {
return true
} else {
return false
}
}
我们使用jasmine测试框架,具体api参考 jasmine api,test.js中的内容:
describe('index.js: ', function() {
it('isNum() should work fine.', function() {
expect(isNum(1)).toBe(true)
expect(isNum('1')).toBe(false)
})
})
➜ karma karma start
29 12 2016 11:38:15.620:WARN [karma]: No captured browser, open http://localhost:9876/
29 12 2016 11:38:15.634:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
29 12 2016 11:38:15.635:INFO [launcher]: Launching browser Chrome with unlimited concurrency
29 12 2016 11:38:15.651:INFO [launcher]: Starting browser Chrome
29 12 2016 11:38:16.648:INFO [Chrome 55.0.2883 (Mac OS X 10.12.1)]:Connected on socket /#Kc8j_hOrgXwvl7afAAAA with id 26739205
Chrome 55.0.2883 (Mac OS X 10.12.1): Executed 1 of 1 SUCCESS (0.005 secs / 0.001 secs)
npm i --save-dev karma-coverage
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'src/*.js',
'test/*.js'
],
exclude: [],
// modified
preprocessors: {
'src/*.js': ['coverage']
},
//modified
reporters: ['progress', 'coverage'],
// add
coverageReporter: {
type : 'html',
dir : 'coverage/'
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
再运行karma start,在目录下生成coverage目录,里面有本次测试的覆盖报告,如下: