Karma 官方介紹 A simple tool that allows you to execute JavaScript code in multiple real browsers. 即一個允許你在多個真實瀏覽器中執行js代碼的簡單工具。 使用了karma之後,我們之前為了Enzyme的mou ...
Karma
官方介紹
A simple tool that allows you to execute JavaScript code in multiple real browsers.
即一個允許你在多個真實瀏覽器中執行js代碼的簡單工具。
使用了karma之後,我們之前為了Enzyme的mount而要求的環境就不需要用jsdom去模擬了,因為karma就是將測試js在真實瀏覽器中執行的。
安裝:
npm i --save-dev karma karma-chai karma-webpack karma-mocha karma-chrome-launcher
npm i karma -g
npm install -g karma-cli //window命令行運行,如果顯示不能發現webpack那麼需要安裝這個
然後配置karma:
karma init
以下為我的配置:
// Karma configuration
// Generated on Fri Feb 02 2018 10:07:20 GMT+0800 (中國標準時間)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha','chai'],
// list of files / patterns to load in the browser
files: [
'src/**/*.js',
'src/**/*.jsx',//不知道為什麼,karma無法識別jsx
'test/*.test.js'
],
// list of files / patterns to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/**/*.js': ['webpack'],
//'src/**/*.jsx':['webpack'],//不知道為什麼,karma無法識別jsx
'test/*.test.js': ['webpack']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
webpack: {
module: {
rules: [{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
}
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
}]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader']
}
]
}
}
})
}
一點小疑惑,在用kamar的時候正則表達式匹配不到jsx文件,於是將項目內部的jsx文件都改為js就好了。
因為更喜歡jest的方式,所以對karma這種使用到瀏覽器的沒有做更深入的研究,只是有所瞭解就夠了。