【前端单元测试入门04】Karma
程序员文章站
2022-07-10 17:44:51
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这种使用到浏览器的没有做更深入的研究,只是有所了解就够了。
上一篇: 联想手机新品预告:目标直指Redmi Note 9系列
下一篇: 设计模式之简单工厂模式