react项目进行jest自动化测试配置

引入jest

npm i jest -D

// 兼容es5在node_modules下模块化引入css

npm i -D identity-obj-proxy //fix bug when importing antd-mobile by babel dynamic error: Cannot use import statement outside a modul

初始化jest

jest --init // 根目录下运行

结果导向 => 根目录下创建jest.config.js,根据选项加载相应npm依赖包, 并根据需求配置一下匹配项目 jest.config.js

module.exports = { //设置输出报告 collectCoverage: true, //报告输出路径 coverageDirectory: 'www/tests', // 测试运行环境 jest --init未加载依赖成功的话,必须报错缺少依赖,命令行提示手动加载依赖 testEnvironment: 'jsdom', // 匹配的文件会运行到测试库中 testMatch: [ '<rootDir>/app/**/__tests__/**/*.{spec,test}.{js,jsx,ts,tsx}', '<rootDir>/app/**/*.{spec,test}.{js,jsx,ts,tsx}', ], //对于jest而言,很多文件都是解析不了的,区分文件处理器 transform: { '^.+.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/babel-jest', '^.+.(css|less)$': 'jest-less-loader', '\.(jpg|jpeg|png|gif|webp|svg)$': '<rootDir>/fileTransformer.js', // fileTransformer.js处理jest图片路径 }, //告诉jest要处理哪些文件 moduleFileExtensions: [ 'jsx', 'js', 'tsx', 'ts', 'json', ], // 对于打包工具,常常使用别名的方式优化项目导入路径 // 例如webpack中 /* resolve: { extensions: ['.js', '.jsx'], alias: { '@fo': path.resolve(__dirname, '../app/components'), } */ moduleNameMapper: { // '@network': '<rootDir>/app/network', // '@pages': '<rootDir>/app/pages', // '@': path.resolve(__dirname, '../app'), "@images/*(.*)$": "<rootDir>/app/images/$1", "@fo/*(.*)$": "<rootDir>/app/components/$1", "@common/*(.*)$": "<rootDir>/app/common/$1", "\\.(css|less)$": 'identity-obj-proxy',//fix bug when importing antd-mobile by babel dynamic error: Cannot use import statement outside a modul }, };

处理项目中图片资源

/fileTransformer.js

``` /fileTransformer.js const path = require('path');

module.exports = { process(sourceText, sourcePath, options) { return { code: module.exports = ${JSON.stringify(path.basename(sourcePath))};, }; }, }; ```

处理node_modules中模块化引入的css模块

根目录下babel配置文件中添加配置项统一commonjs的使用 .babelrc 文件

{ "presets": [ "@babel/preset-env", ["@babel/preset-react", { "runtime": "automatic"} ]], "env": { "test": { "plugins": [ ["import", { "libraryName": "antd-mobile", "libraryDirectory": "cjs/components", "style": false}] ] } } }

相关测试npm依赖工具

npm i @testing-library/react -D react18 需要13+版本 react18- 需要12版本

运行

npm run test

scripts": { "test": "jest --watch", }

import React from 'react'; import {Button} from "antd-mobile"; import {render, queryByText} from "@testing-library/react"; describe( '',() => { render(); test('', () => { expect(!!document.querySelector('button')).toBe(true) }) }); ``` image.png

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百度一下吧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值