初探:使用Jest进行React单元测试
admin
2024-02-29 09:33:27

在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

相关内容

热门资讯

QQ:23周年QQ秀回归,新增... 【1月24日QQ宣布QQ秀回归,更新亮点多且近期动作频频】1月24日,QQ官宣QQ秀回归,用户在手机...
最新或2023(历届)鲁迅美术... 鲁迅美术学院前身是1938年建于延安的鲁迅艺术学院,由毛泽东、周恩来等老一代领导人亲自倡导创建。毛泽...
最新或2023(历届)华北电力... 华北电力大学科技学院成立于2002年6月,是国家教育部和河北省人民政府批准设立,由国家“211工程”...
最新或2023(历届)河北医科... 河北医科大学临床学院是河北省人民政府2001年7月批准成立的13所独立学院之一,由河北医科大学主办,...
最新或2023(历届)河北经贸... 河北经贸大学经济管理学院是由河北经贸大学按照新机制、新模式创办的一所全日制本科独立学院。  学院位于...