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

本文案例githubhttps://github.com/axel10/react-jest-typescript-democss

 

配置jestreact测试环境时咱们能够参考官方的配置教程:react

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

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

若是要兼容typescript项目,能够参考ts-jest提供的教程:web

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

 

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

1:若是在测试中使用了enzyme则须要配置启动文件,不然报错:json

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

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

 

test.setup.jsless

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”,不然会报语法没法识别的错误。

相关文章
相关标签/搜索