Files
nahodka-front/src/components/MapView.test.jsx
SlimusMinus 6dc61050d9
Some checks failed
deploy-frontend / deploy (push) Failing after 11s
Add Docker build and deploy pipeline
2026-10-07 23:27:38 +03:00

240 lines
7.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Регрессия: первая загрузка маркеров должна уходить с границами карты.
*
* Раньше первый запрос висел на map.events.add('load'), которого у ymaps.Map
* в 2.1 нет — событие не наступало, fetch не уходил, а спиннер закрывал
* карту навсегда. Фейковый ymaps ниже намеренно НЕ умеет в 'load'.
*/
import { render, screen, waitFor, act } from "@testing-library/react";
import MapView from "./MapView";
// Реальный i18n, а не заглушка: MapView использует t() и без инициализации
// react-i18next сыплет предупреждение, а проверка текста ошибки теряла бы смысл.
import "../i18n";
jest.mock("../hooks/useGeolocation", () => ({
GEO_STATUS: {
IDLE: "idle",
LOADING: "loading",
SUCCESS: "success",
DENIED: "denied",
UNSUPPORTED: "unsupported",
TIMEOUT: "timeout",
},
// Геолокация в тестах не нужна и капризна (navigator.geolocation).
useGeolocation: () => ({ coords: null, status: "idle", requestLocation: jest.fn() }),
}));
const BOUNDS = [[55.7, 37.55], [55.8, 37.7]];
function installFakeYmaps({ boundsInitiallyNull = true } = {}) {
const listeners = {};
let bounds = boundsInitiallyNull ? null : BOUNDS;
const map = {
events: {
add(name, cb) {
(listeners[name] = listeners[name] || []).push(cb);
return { name, cb };
},
remove(sub) {
listeners[sub.name] = (listeners[sub.name] || []).filter((cb) => cb !== sub.cb);
},
},
geoObjects: { add() {}, removeAll() {} },
getBounds: () => bounds,
setCenter: jest.fn(),
destroy: jest.fn(),
};
window.ymaps = {
ready: (cb) => cb(),
Map: jest.fn(() => map),
GeoObjectCollection: jest.fn(function GeoObjectCollection() {
this.add = jest.fn();
this.removeAll = jest.fn();
}),
Placemark: jest.fn(function Placemark() {
this.events = { add() {} };
this.geometry = { setCoordinates() {} };
}),
templateLayoutFactory: { createClass: jest.fn(() => function Layout() {}) },
};
return {
map,
/** Имитирует первый расчёт вьюпорта — так ведёт себя настоящий API. */
publishBounds() {
bounds = BOUNDS;
act(() => {
(listeners.boundschange || []).forEach((cb) => cb());
});
},
panTo(next) {
bounds = next;
act(() => {
(listeners.boundschange || []).forEach((cb) => cb());
});
},
fireBoundsChangeOnly() {
act(() => {
(listeners.boundschange || []).forEach((cb) => cb());
});
},
};
}
let fetchMock;
beforeEach(() => {
jest.useFakeTimers();
fetchMock = jest.fn().mockResolvedValue({
ok: true,
json: async () => [
{ id: 1, latitude: 55.75, longitude: 37.61, type: "LOST", title: "Кошелёк" },
],
});
global.fetch = fetchMock;
});
afterEach(() => {
jest.useRealTimers();
delete window.ymaps;
jest.clearAllMocks();
});
function mapCall(index = 0) {
const url = fetchMock.mock.calls[index]?.[0] || "";
return new URL(url, "http://localhost");
}
test("первый запрос уходит с границами карты, а не пустым query", async () => {
const ymaps = installFakeYmaps();
render(<MapView focusPostId={null} focusLat={NaN} focusLng={NaN} onBack={() => {}} />);
// Границы появляются только после первого расчёта вьюпорта.
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
const url = mapCall();
expect(url.pathname).toBe("/api/v1/posts/map");
expect(url.searchParams.get("minLat")).toBe("55.7");
expect(url.searchParams.get("minLng")).toBe("37.55");
expect(url.searchParams.get("maxLat")).toBe("55.8");
expect(url.searchParams.get("maxLng")).toBe("37.7");
});
test("все четыре граничных параметра присутствуют в каждом запросе", async () => {
const ymaps = installFakeYmaps();
render(<MapView onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalled());
for (const call of fetchMock.mock.calls) {
const url = new URL(call[0], "http://localhost");
for (const key of ["minLat", "maxLat", "minLng", "maxLng"]) {
expect(url.searchParams.get(key)).not.toBeNull();
}
}
});
test("опциональные фильтры type/category уезжают в том же запросе", async () => {
const ymaps = installFakeYmaps();
render(<MapView type="LOST" category="Электроника" onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
const url = mapCall();
expect(url.searchParams.get("type")).toBe("LOST");
expect(url.searchParams.get("category")).toBe("Электроника");
expect(url.searchParams.get("minLat")).toBe("55.7");
});
test("фильтры не добавляются, когда не заданы", async () => {
const ymaps = installFakeYmaps();
render(<MapView onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
const url = mapCall();
expect(url.searchParams.has("type")).toBe(false);
expect(url.searchParams.has("category")).toBe(false);
});
test("перемещение карты перезапрашивает маркеры один раз, несмотря на debounce", async () => {
const ymaps = installFakeYmaps();
render(<MapView onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
// Серия boundschange без пауз — должна схлопнуться в один запрос.
ymaps.fireBoundsChangeOnly();
ymaps.fireBoundsChangeOnly();
ymaps.fireBoundsChangeOnly();
expect(fetchMock).toHaveBeenCalledTimes(1);
await act(async () => {
jest.advanceTimersByTime(400);
});
// Новые границы = ровно один новый запрос.
ymaps.panTo([[55.9, 37.4], [56.0, 37.5]]);
await act(async () => {
jest.advanceTimersByTime(400);
});
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
const url = mapCall(1);
expect(url.searchParams.get("minLat")).toBe("55.9");
expect(url.searchParams.get("maxLng")).toBe("37.5");
});
test("одинаковые границы не порождают повторный запрос", async () => {
const ymaps = installFakeYmaps();
render(<MapView onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
ymaps.fireBoundsChangeOnly();
await act(async () => {
jest.advanceTimersByTime(400);
});
expect(fetchMock).toHaveBeenCalledTimes(1);
});
test("спиннер снимается и карта не остаётся закрыта оверлеем", async () => {
const ymaps = installFakeYmaps();
render(<MapView onBack={() => {}} />);
ymaps.publishBounds();
await waitFor(() => expect(fetchMock).toHaveBeenCalled());
await waitFor(() => {
expect(screen.queryByTestId("mapview-loading")).toBeNull();
});
expect(screen.queryByText("Ошибка загрузки карты")).toBeNull();
});
test("даже если границы так и не пришли, карта не висит в вечной загрузке", async () => {
installFakeYmaps();
render(<MapView onBack={() => {}} />);
await waitFor(
() => {
expect(screen.queryByTestId("mapview-loading")).toBeNull();
},
{ timeout: 8000 }
);
});