React Jest单元测试配置

1. 测试项目环境

项目基于Ant design pro,antd 3.23.1,js。
测试依赖:
注意版本,以下几个是测试通过的,如果要更换版本,先查看或测试兼容性。
package.json中添加开发环境依赖

"devDependencies": {
    
    
	"jest": "^27.2.5",
  "babel-jest": "^27.2.5",
  "@babel/core": "^7.12.16",
  "@babel/preset-env": "^7.12.16",
  "@babel/preset-react": "^7.12.13"
}

2. 相关配置

2.1 jest 配置

配置项参考文档:jest配置项

  1. rootDir 项目根目录,根据自己 jest-config.js 位置决定。
  2. collectCoverage 是否进行覆盖测试,这里没有开启,覆盖测试相关以coverage打头的字段,详细查询配置项文档。
  3. moduleNameMapper 配置,主要解决Cannot find module’@common/utils’ from ‘index.js’ 问题,webpack的resolve.alias设置了@**的别名,这里jest需要配置模块名称映射,将@这些名称映射到真正的文件上。
  4. testMatch 配置测试文件格式,这里我配置的是任意路径下的 *.test.js 文件均为单元测试文件。
  5. setupFiles 解决一些环境依赖问题,例如关于window(浏览器对象模型)的依赖,我在项目中使用了 localStorage,单元测试没有启用浏览器,因此会报错,setupFiles 是在测试之前需要加载的代码,和Java单元测试之前装载spring环境一个道理。**
  6. testUrl 项目开发环境运行地址。
  7. 其余配置参考文档。
const path = require('path');

module.exports = {
    
    
  rootDir: path.resolve(__dirname, './'),
  collectCoverage: false,
  collectCoverageFrom: ['<rootDir>/src/**/*.{js,jsx,mjs}'],
  coverageDirectory: '<rootDir>/test/coverage',
  coveragePathIgnorePatterns: ['/node_modules/', '<rootDir>/src/page/index.js'],
  moduleNameMapper: {
    
    
    '^@/(.*)$': '<rootDir>/src/$1',
    '^@@/(.*)$': '<rootDir>/src/.umi/$1',
  },
  setupFiles: ['<rootDir>/test/setup.js'],
  testMatch: [ "**/*.test.js?(x)"],
  testURL: 'http://localhost:8000',
  transform: {
    
    
    '^.+\\.(js|jsx|mjs)$': '<rootDir>/node_modules/babel-jest',
    '^.+\\.(css|less)$': '<rootDir>/test/cssTransform.js',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/test/fileTransform.js',
  },
  transformIgnorePatterns: [
    '[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$',
  ],
};

2.2 jest 配置中的加载的js文件

以下文件位置参考 2.1中的配置。

  1. 测试运行前安装脚本 setup.js
/**
 * 配置单元测试localStorage
 */
const localStorageMock = {
    
    
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn()
};
global.localStorage = localStorageMock;
  1. 防止样式解析错误影响单元测试 cssTransform
/**
 * 所有样式文件重定向,返回空
 */
module.exports = {
    
    
  process() {
    
    
    return 'module.exports = {};';
  },
  getCacheKey() {
    
    
    return 'cssTransform';
  },
};
  1. 忽略文件(图片、字体等)fileTransform.js
/**
 * 忽略文件
 */
const path = require('path');

module.exports = {
    
    
  process(src, filename) {
    
    
    return `module.exports = ${
      
      JSON.stringify(path.basename(filename))};`;
  },
};

2.3 babel 配置

项目根目录下创建.babelrc文件(也可在package.json中配置),内容如下:
如果使用 env和react 会报找不到preset-react的错误。

{
    
    
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

3. 测试

3.1 工具文件

utils.js 可以在文件中引入一些模块来充分测试。

/**
 * 数字补0
 * @param val 整型数字
 */
export function fixedZero(val) {
    
    
  return val * 1 < 10 ? `0${
      
      val}` : val;
}

3.2 单元测试

utils.test.js 也可以直接使用console.log()打印在控制台。

import {
    
     fixedZero, isUrl } from '@/common/utils';

describe('测试功能描述:自动填充数字(补0)', () => {
    
    
  it('预期结果描述:10以上的数字不会补0', () => {
    
    
    expect(fixedZero(10)).toEqual(10);
    expect(fixedZero(11)).toEqual(11);
    expect(fixedZero(15)).toEqual(15);
    expect(fixedZero(20)).toEqual(20);
    expect(fixedZero(100)).toEqual(100);
    expect(fixedZero(1000)).toEqual(1000);
  });

  it('预期结果描述:个位数字前面补0,并以字符串输出', () => {
    
    
    expect(fixedZero(0)).toEqual('00');
    expect(fixedZero(1)).toEqual('01');
    expect(fixedZero(2)).toEqual('02');
    expect(fixedZero(3)).toEqual('03');
    expect(fixedZero(4)).toEqual('04');
    expect(fixedZero(5)).toEqual('05');
    expect(fixedZero(6)).toEqual('06');
    expect(fixedZero(7)).toEqual('07');
    expect(fixedZero(8)).toEqual('08');
    expect(fixedZero(9)).toEqual('09');
  });
});

猜你喜欢

转载自blog.csdn.net/wizard_rp/article/details/120917644