Change test render method to use locationService

This commit is contained in:
Tom Ratcliffe 2024-04-26 15:45:48 +01:00 committed by Tom Ratcliffe
parent a34c02fcf2
commit 31231cf5bf

View File

@ -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<typeof MemoryRouter>;
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 (
<Provider store={reduxStore}>
<GrafanaContext.Provider value={context}>
<PotentialRouter {...routerOptions}>
<PotentialRouter history={history}>
<ModalsContextProvider>{children}</ModalsContextProvider>
</PotentialRouter>
</GrafanaContext.Provider>