在React项目里,如果你使用 Create React App,Jest 已经能够开箱即用且包含许多实用的默认配置。
在src文件夹目录下,有setupTests.js文件
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
写单元测试(示例):
mock.js
export function helloWorld() {return 'helloWorld';
}
mock.test.js
import { helloWorld } from './mock'test('adds 1 + 2 to equal 3', done => {expect(helloWorld()).toBe('helloWorld');done()
});afterAll(done => { done() })
执行npm run test 进行单元测试
"test": "craco test --watchAll=false --coverage --collectCoverageFrom=src/mock/* --ci --reporters=default --reporters=jest-junit --forceExit"
会在根目录下生成coverage文件夹,里面有index.html 文件可以打开查看覆盖率
使用craco进行配置开发:
package.json
"scripts": {"dev": "GENERATE_SOURCEMAP=false cross-env PORT=5000 craco start","prd": "GENERATE_SOURCEMAP=false dotenv -e .env.production craco start","test2": "craco test --watchAll=false --coverage --ci --reporters=default --reporters=jest-junit --forceExit","test": "craco test --watchAll=false --coverage --collectCoverageFrom=src/mock/* --ci --reporters=default --reporters=jest-junit --forceExit","build": "GENERATE_SOURCEMAP=false craco build","build:dev": "dotenv -e .env.development craco build","build:dev-local": "dotenv -e .env.development.local craco build","build:test": "dotenv -e .env.test craco build","start-old": "cross-env PORT=5000 react-scripts start","build-old": "react-scripts build","test-old": "react-scripts test","eject": "react-scripts eject"},
craco.config.js文件里可以配置jest参数
module.exports = {webpack: {// 别名配置alias: {'@': pathResolve('src'),},module: {rules: [{// js 文件才使用 babeltest: /\.js$/,// 只在 src 文件夹下查找include: [pathResolve('src')],// 不会去查找的路径exclude: /node_modules/,use: [{loader: 'thread-loader',},{loader: 'babel-loader',options:{// 开启babel缓存// 第二次构建时,会读取之前的缓存cacheDirectory: true} }]}]},/*** 重写 webpack 任意配置* - configure 能够重写 webpack 相关的所有配置,但是,仍然推荐你优先阅读 craco 提供的快捷配置,把解决不了的配置放到 configure 里解决;* - 这里选择配置为函数,与直接定义 configure 对象方式互斥;*/configure: (webpackConfig, {env, paths}) => {// paths.appPath='public'paths.appBuild = outputDirName // 配合输出打包修改文件目录// webpackConfig中可以解构出你想要的参数比如mode、devtool、entry等等,更多信息请查看webpackConfig.json文件/*** 修改 output*/webpackConfig.output = {...webpackConfig.output,path: path.resolve(__dirname, outputDirName), // 修改输出文件目录publicPath: process.env.REACT_APP_PUBLICPATH // 设置的是部署应用包的基本 URL,不是项目打包出来的文件存放的位置}// 返回重写后的新配置// return smp.wrap(webpackConfig)return webpackConfig},plugins: [// new SpeedMeasurePlugin(),// compression-webpack-plugin 因为版本问题,2.x将 asset 改为了 filename// new CompressionPlugin({// filename: '[path].gz[query]', // 目标资源名称。[file] 会被替换成原资源。[path] 会被替换成原资源路径,[query] 替换成原查询字符串// algorithm: 'gzip', // 算法 // test: new RegExp('\\.(js|css)$'), // 压缩 js 与 css// threshold: 10240, // 只处理比这个值大的资源。按字节计算// minRatio: 0.8 // 只有压缩率比这个值小的资源才会被处理// }),// new HardSourceWebpackPlugin() // 解决打包慢的问题]},plugins: [{plugin: CracoLessPlugin,options: {lessLoaderOptions: {lessOptions: {modifyVars: { // '@primary-color': '#1DA57A','@heading-color': '#1890ff' // 标题色},javascriptEnabled: true,},},},}],jest: {collectCoverageFrom: ['src/mock/*']}
}
使用到的插件文档:
craco官方文档:Welcome | CRACO
jest官方文档:全局设定 · Jest