Jest+Enzyme React js/typescript测试环境配置案例

本文案例github:https://github.com/axel10/react-jest-typescript-demo

配置jest的react测试环境时我们可以参考官方的配置教程:

https://jestjs.io/docs/zh-Hans/getting-started

https://jestjs.io/docs/zh-Hans/tutorial-react

如果要兼容typescript项目,可以参考ts-jest提供的教程:

https://github.com/basarat/typescript-book/blob/master/docs/testing/jest.md

这里对案例中一些可能说的不是很清楚的地方进行一下讲解:

1:如果在测试中使用了enzyme则需要配置启动文件,否则报错:

先在jest.config.js中配置setFiles选项:

"setupFiles": [
  "<rootDir>/test.setup.js"
],

test.setup.js:

import * as enzyme from 'enzyme';
import ReactSixteenAdapter from 'enzyme-adapter-react-16';

enzyme.configure({ adapter: new ReactSixteenAdapter() });

2:如果react组件中import了静态资源或者启用了css module则需要在jest.config.js配置moduleNameMapper选项:

moduleNameMapper: {
  "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
  "\\.(css|less|scss)$": "identity-obj-proxy"
},

fileMock.js:

module.exports = 'test-file-stub'; // 导出一个字符串以模拟url

identity-obj-proxy是一个npm包,需要安装。

npm i identity-obj-proxy -D

3:如果启用了typescript兼容,除了根据官方案例进行配置以外,还需要在tsconfig.json中将”jsx”选项配置为”react”,否则会报语法无法识别的错误。