javascript - React Native - Jest - Enzyme 抛出 Jest 无法解析错误
问题描述
当我想将 Jest 和 Enzyme 作为测试库添加到我的 React Native 项目时,我遇到了一个错误。这是我的代码:
//Button.spec.js
import React from 'react';
import { View } from 'react-native';
import { shallow } from 'enzyme';
const Test = () => <View />;
describe('SomeComponent component', () => {
it('Shallow rendering', () => {
const wrapper = shallow(<Test />);
});
});
//jest/setup.js
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
//babel.config.js
module.exports = () => ({
presets: ['module:metro-react-native-babel-preset'],
plugins: ['transform-flow-strip-types']
});
//jest.config.json
{
"preset": "react-native",
"collectCoverage": true,
"moduleDirectories": [
"node_modules",
"src"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
"setupFiles": [
"<rootDir>/jest/setup.js"
],
"transformIgnorePatterns": [
"/node_modules/(?!react-native|).+\\.js$"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"/jest"
]
}
当我跑步时npm test
。它会抛出这样的错误:
/src/components/common/__test__/Button.spec.js: Unexpected token (5:19)
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
3 | import { shallow } from 'enzyme';
4 |
> 5 | const Test = () => <View />;
| ^
6 |
7 | describe('SomeComponent component', () => {
8 | it('Shallow rendering', () => {
你们有什么建议来解决这个问题吗?我应该添加我在 node_modules 中使用的任何库transformIgnorePatterns
吗?或者是否缺少设置步骤?
解决方案
推荐阅读
- python - Python os.walk 返回码
- mysql - 在服务器重启 Node/Express 之前调用一个函数
- python - Python中的最小/最大堆实现
- forms - Mailchimp:如何捕获更新配置文件表单提交日期
- php - 使用 PHPmyadmin 和 SQL 检查计划可用性的方法和算法
- r - 在 R 中处理嵌套列表
- mongodb - 带有 Spring Data 的 MongoDB - 检查条件是否为空
- c++ - 从 Money 类转换为 Int 失败
- flutter - Android SDK 缺少命令行工具
- java - 你如何“打印”一个处理不可打印值的字节数组