引入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) }) }); ```