如何在单元测试中模拟useMapEvents(由react-leaflet提供)

问题描述 投票:0回答:1

我试图创建一个新的单元测试来模拟 UseMapEvents,但收到一条错误消息,指出“ReferenceError:初始化之前无法访问‘地图’”。

您有解决这个问题的方法吗?

如果您需要了解 UseMapEvent 是什么,请查看

https://react-leaflet.js.org/docs/api-map/#usemapevents

组件

function MyComponent() { const map = useMapEvents({ click: () => { map.locate() }, }) return null } function MyMapComponent() { return ( <MapContainer center={[50.5, 30.5]} zoom={13}> <MyComponent /> </MapContainer> ) }

单元测试

import { useMapEvents } from 'react-leaflet'; import MyMapComponent from '.'; jest.mock('react-leaflet', () => ({ ...jest.requireActual('react-leaflet'), useMapEvents: jest.fn().mockImplementation((f) => f()), })); it('renders region layer without crashing', async () => { useMapEvents.mockImplementation((handlers) => { handlers.click(); }); await act(async () => render(<MyMapComponent />)); });
我尝试运行测试,但是错误消息“

ReferenceError:初始化之前无法访问‘地图’”阻止了我通过测试。

请查看下面的屏幕截图。

enter image description here

jestjs react-testing-library react-leaflet react-testing
1个回答
0
投票
这是我的

vitest

 设置文件中的一个片段,它在使用 
useMapEvents
 时模拟 
react-leaflet 4.2.1
 处理程序的子集。

vi.mock("react-leaflet/hooks", async (importOriginal) => { const mod = await importOriginal<typeof import("react-leaflet/hooks")>(); return { ...mod, useMapEvents: vi.fn((events) => { useEffect(() => { const handlers: { [key: string]: ( e: Event | LeafletMouseEvent | LeafletKeyboardEvent, ) => void; } = {}; Object.keys(events).forEach((event) => { const handler = ( e: Event | LeafletMouseEvent | LeafletKeyboardEvent, ) => { let leafletEvent; if (event === "dblclick" || event === "contextmenu") { leafletEvent = { originalEvent: e, type: event, target: e.target, latlng: new LatLng(0, 0), layerPoint: new Point(0, 0), containerPoint: new Point(0, 0), sourceTarget: e.target, popup: null, layer: null, propagatedFrom: null, }; } else if (event === "keydown") { leafletEvent = { originalEvent: e, type: "keydown", target: e.target, layer: "", popup: "", sourceTarget: e.target, propagatedFrom: "", }; } else if (event === "selectarea:selected") { leafletEvent = { type: event, bounds: new LatLngBounds( new LatLng(1, 1), new LatLng(10, 10), ), start: new LatLng(1, 1), end: new LatLng(10, 10), sourceTarget: {}, target: {}, }; } events[event](leafletEvent); }; document.addEventListener(event, handler); handlers[event] = handler; }); // Cleanup function to remove event listeners return () => { Object.keys(handlers).forEach((event) => { document.removeEventListener(event, handlers[event]); }); }; }, [events]); return null; }), }; });
    
© www.soinside.com 2019 - 2024. All rights reserved.