测试 React Leaflet 时的地图大小

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

我正在尝试测试自定义的反应传单组件。它抓取地图元素并使用过滤器来获取当前缩放级别下可见的元素数量:

const visible = allPoints.filter(p => map.getBounds().contains(p));

此代码在应用程序中运行良好,但是当我尝试使用 Jest & Enzyme 进行测试时,过滤器始终返回 0 个元素,无论缩放级别如何。稍微研究了一下,我发现

map.getSize()
总是返回 0x0,而
map.getBounds()
对于西南角和东北角返回相同的点,这解释了为什么它不能真正包含任何其他点。

这只是 Enzyme 或 Leaflet 中的一个错误,还是我需要做一些事情来明确设置地图大小?

import React from "react";
import { mount } from "enzyme";
import { act } from "react-dom/test-utils";
import { MapContext } from "../../../context";
import MarkersShown from "../markers-shown";
import { Map } from "react-leaflet";
import { mockParsed, mockCenter, mockData } from "./__data__";

describe("MarkersShown Tests", () => {
    it("renders the total asset count", async () => {
        const parsed = mockParsed;
        const center = mockCenter;
        let wrapper;
        await act(async () => {
            wrapper = mount(
                <MapContext.Provider value={mockData}>
                    <Map zoom={parsed.z} center={center} style={{ height: "100px", width: "100px" }}>
                        <MarkersShown />
                    </Map>
                </MapContext.Provider>
            );
        });
        wrapper.update();
        expect(wrapper.html()).toEqual(
            expect.stringMatching("Markers Shown of 3")
        );
    });
});
react-leaflet
1个回答
0
投票

这是因为jsdom不支持

clientWidth
/
clientHeight
,而
getSize
所依赖的。

一个可怕的解决方法:

import { Map, Point } from 'leaflet'

beforeEach(() => {
  jest.spyOn(Map.prototype, 'getSize').mockImplementation(() => new Point(500, 500))
})
© www.soinside.com 2019 - 2024. All rights reserved.