From 31231cf5bf5c966f468b000827687d41bef62f05 Mon Sep 17 00:00:00 2001 From: Tom Ratcliffe Date: Fri, 26 Apr 2024 15:45:48 +0100 Subject: [PATCH] Change test render method to use locationService --- public/test/test-utils.tsx | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/public/test/test-utils.tsx b/public/test/test-utils.tsx index b27a0666b54..ee6d2b6c2e7 100644 --- a/public/test/test-utils.tsx +++ b/public/test/test-utils.tsx @@ -1,12 +1,14 @@ import { ToolkitStore } from '@reduxjs/toolkit/dist/configureStore'; import { render, RenderOptions } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import React, { ComponentProps, Fragment, PropsWithChildren } from 'react'; +import { createMemoryHistory, MemoryHistoryBuildOptions } from 'history'; +import React, { Fragment, PropsWithChildren } from 'react'; import { Provider } from 'react-redux'; -import { MemoryRouter } from 'react-router-dom'; +import { Router } from 'react-router-dom'; import { PreloadedState } from 'redux'; import { getGrafanaContextMock } from 'test/mocks/getGrafanaContextMock'; +import { HistoryWrapper, setLocationService } from '@grafana/runtime'; import { GrafanaContext, GrafanaContextType } from 'app/core/context/GrafanaContext'; import { ModalsContextProvider } from 'app/core/context/ModalsContextProvider'; import { configureStore } from 'app/store/configureStore'; @@ -29,9 +31,9 @@ interface ExtendedRenderOptions extends RenderOptions { */ renderWithRouter?: boolean; /** - * Props to pass to `MemoryRouter`, if being used + * Props to pass to `createMemoryHistory`, if being used */ - routerOptions?: ComponentProps; + historyOptions?: MemoryHistoryBuildOptions; } /** @@ -41,7 +43,7 @@ interface ExtendedRenderOptions extends RenderOptions { const getWrapper = ({ store, renderWithRouter, - routerOptions, + historyOptions, grafanaContext, }: ExtendedRenderOptions & { grafanaContext?: GrafanaContextType; @@ -50,7 +52,13 @@ const getWrapper = ({ /** * Conditional router - either a MemoryRouter or just a Fragment */ - const PotentialRouter = renderWithRouter ? MemoryRouter : Fragment; + const PotentialRouter = renderWithRouter ? Router : Fragment; + + // Create a fresh location service for each test - otherwise we run the risk + // of it being stateful in between runs + const history = createMemoryHistory(historyOptions); + const locationService = new HistoryWrapper(history); + setLocationService(locationService); const context = { ...getGrafanaContextMock(), @@ -65,7 +73,7 @@ const getWrapper = ({ return ( - + {children}