元素类型在react jest中具有react-小叶时无效

vof42yt1  于 2022-12-25  发布在  Jest
关注(0)|答案(1)|浏览(192)

我尝试使用jest来测试文档中的链接,但是测试失败,元素类型无效。为什么从“react-leaflet”导入在jest中未定义?
我的测试

import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
  render(
    <App />
  )
  const linkElement = screen.getByText("map-btn");
  expect(linkElement).toBeInTheDocument();
});

以及App.js

import React, { useState, useEffect } from "react"
import { MapContainer, TileLayer, Marker, Popup, useMap, Circle } from 'react-leaflet'
import L from 'leaflet'

function App(){

    return (
      <div className={'col-md-8'}>
        <div>
          <MapContainer center={[25.033671, 121.564427]} zoom={17} style={{height: '100vh'}} >
          <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <Marker position={[25.033671, 121.564427]}>
            <Popup>current position</Popup>
          </Marker>
          </MapContainer>
        </div>
      </div>
    )
}

export default App

0g0grzrc

0g0grzrc1#

我有一个几乎相同的设置。解决这个问题的方法是安装jest-canvas-mock模块,然后将其包含在我的src/setupTest.js文件中,如下所示:

import '@testing-library/jest-dom';
import 'jest-canvas-mock';

然后,我能够模拟出包含应用程序中使用的react-leaflet组件的实际div,并测试应用程序是否正确呈现:

import React from 'react';
import { render, screen } from '../src/test-utils';
import App from './App';

jest.mock('./components/MapComponent', () => () =><div>MapComponentMock</div>);

test('renders the app', () => {
  render(<App />);
  const headerLogo = screen.getByAltText(/logo/i);
  expect(headerLogo).toBeInTheDocument();

  const searchButton = screen.getByRole('button', {name: /search/i});
  expect(searchButton).toBeInTheDocument();

});

相关问题