Problem testing react component that implement react-leaflet map with jest
Asked Answered
B

2

8

I have the following issue when I tried to test a react components that implement the react-leaflet library

    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 internet and the recommendations I found don't work for me.

This error happen when I tried to render any component that has a relation with that library, for example, 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

Bilinear answered 27/6, 2022 at 2:56 Comment(1)
You can try the solution described here: #49263929Roxannaroxanne
D
6

In your jest.config.js add these lines

"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

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

module.exports = {
    useMapEvents: () => {}
}
Dynah answered 7/9, 2022 at 14:29 Comment(0)
C
0

I've solved this problem with mocking react-leaflet in my test file

jest.mock('react-leaflet', () => jest.fn());
Cubicle answered 16/4 at 20:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.