karma-cli
karma
命令npm install -g karma-cli
复制代码
npm install -S karma
复制代码
karma-mocha
:若想驱动mocha
框架进行测试,就必须安装karma-mocha
;其余不一样的单元测试框架分别也有本身对于的插件karma-chrome-launcher
:提供了karma与chrome的适配器
karma
选择什么浏览器进行测试,就须要安装对于的适配器插件npm install -S karma-mocha karma-chrome-launcher
复制代码
karma init
,进行配置选择1. Which testing framework do you want to use ? (mocha)
2. Do you want to use Require.js ? (no)
3. Do you want to capture any browsers automatically ? (Chrome)
4. What is the location of your source and test files ? (https://cdn.bootcss.com/jquery/2.2.4/jquery.js, node_modules/should/should.js, test/**.js)
5. Should any of the files included by the previous patterns be excluded ? ()
6. Do you want Karma to watch all the files and run the tests on change ? (yes)
复制代码
karma.conf.js
frameworks
:使用到的框架
mocha
框架进行测试,这里就要使用到mocha
files
:能够将待测试代码以及它们须要的依赖加载进来browsers
:须要启动什么浏览器进行测试autoWatch
:是否监听文件变更,若有变更则从新运行单测singleRun
:是否只运行一次测试(设为true
的话,浏览器窗口不会一直维持在,打开进行一次测试后就会关闭了)
singleRun
要配合其余的持续集成工程来使用,必需要设置singleRun=true
,由于持续集成时不须要屡次运行测试// karma.conf.js
module.exports = function(config) {
config.set({
// 跟路径,后面配置的基本全部相对路径都会根据这个路径来构造
basePath: '',
// 使用到的框架,目前karma支持的框架详见 https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
// 会在浏览器中执行的代码:
files: [
'test/main.js',
{
pattern: 'src/**/*.js',
included: false // false 表示初始化的时候不会使用 script 标签直接将相关 js 引入到浏览器,须要本身写代码加载
}
],
// 须要从files中排除掉的文件
exclude: [],
// 须要作预处理的文件,以及这些文件对应的预处理器
preprocessors: {
'src/**/*.js': ['babel', 'coverage'],
'test/**/!(main).js', ['babel', 'coverage'],
'node_modules/protectobject/src/**/*.js': ['babel']
},
// babel预处理器的配置
babelPreprocessor: {
options: {
presets: ['es2015', 'stage-0'],
plugins: ['transform-decorators-legacy', 'transform-es2015-modules-amd']
}
},
// 覆盖率报告器配置:
coverageReporter: {
type: 'html',
dir: 'coverage'
},
// 实际使用什么报告器,全部可用的报告器详见 https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots', 'coverage'],
// 服务器端口号
port: 9876,
// 在输出内容(报告器和日志)中启用/禁用颜色
colors: true,
// 日志级别,可取值 config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO
// 启动/禁用监视文件变化从新执行测试的功能
autoWatch: true,
// 要测试的目标环境
bowers: ['Chrome', 'Firefox', 'Safari'],
// 启动/禁用持续集成模式,启动的话,karma捕获浏览器,运行测试并退出
singleRun: false,
// 并发级别,应该同时启动多少个浏览器
concurrency: Infinity
})
}
复制代码
karma start
复制代码
运行成功: javascript
![]()
files:
What is the location of your source and test files ?
,即将要测试的文件,及测试文件所需的依赖项写入test/main.js
须要使用到jquery.js
karma.conf.js
的files
中填入[jquery.js, test/main.js]
test/main.js
无需手动引入jquery.js
也能使用jquery.js
了require.js
Do you want to use Require.js ? (yes)
require()
语法来引入依赖,在使用Karma
测试时就会报错Uncaught ReferenceError: module is not defined
,Karma
是运行在浏览器端的,不支持Node.js语法