[英]Problem testing react component that implement react-leaflet map with jest
I have the following issue when I tried to test a react components that implement the react-leaflet library当我尝试测试实现 react-leaflet 库的 react 组件时出现以下问题
C:\digital-booking-ui\node_modules\react-leaflet\lib\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { useMap, useMapEvent, useMapEvents } from './hooks.js';
^^^^^^
SyntaxError: Unexpected token 'export'
1 | import React from "react";
2 | import { makeStyles } from "@material-ui/core";
> 3 | import { MapContainer, TileLayer, Marker, Popup, useMap } from "react-leaflet";
| ^
4 |
5 | const Map = () => {
6 | const classes = useStyles();
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/components/accomodation/Map.js:3:1)
I search the problem on the inte.net and the recommendations I found don't work for me.我在 inte.net 上搜索问题,发现的建议对我不起作用。
This error happen when I tried to render any component that has a relation with that library, for example, App.test.js当我尝试呈现与该库有关系的任何组件时会发生此错误,例如 App.test.js
import { render, screen, prettyDOM } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect'
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import { ThemeProvider } from '@material-ui/core';
import theme from "./theme";
let component = null;
beforeEach(() => {
component = render(
<BrowserRouter>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</BrowserRouter>
);
}
);
test('render App', () => {
expect(component).toBeTruthy();
});
How could I fix this?我该如何解决这个问题? It seems a problem of Jest not recognizing the export of the components
这似乎是 Jest 无法识别组件导出的问题
try to replace the below code in your package JSON file:尝试替换 package JSON 文件中的以下代码:
"scripts": {
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!your-module-name)/\"",
},
it will work.它会起作用的。
In your package.json add these lines在您的 package.json 添加这些行
"jest": {
"moduleNameMapper": {
"react-leaflet": "<rootDir>/mocks/reactLeafletMock.js"
}
}
Then in a "mocks" folder (or whatever you want) add a reactLeafletMock.js module that return an empty object然后在“模拟”文件夹(或任何你想要的)中添加一个 reactLeafletMock.js 模块,该模块返回一个空的 object
module.exports = {}
It should be ok (it worked for me)应该没问题(它对我有用)
You could eventually add "react-leaflet" hooks within the object to avoid other errors from Jest您最终可以在 object 中添加“react-leaflet”钩子以避免来自 Jest 的其他错误
module.exports = {
useMapEvents: () => {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.