Skip to content

Instantly share code, notes, and snippets.

@nottyo
Last active February 25, 2022 13:12
Show Gist options
  • Save nottyo/3a5339193aeaa9bfed8a4fee2f16512a to your computer and use it in GitHub Desktop.
Save nottyo/3a5339193aeaa9bfed8a4fee2f16512a to your computer and use it in GitHub Desktop.
React Testing Library - Render with React Router + Redux
import reducer from './reducers';
import { render as rtlRender, RenderOptions } from '@testing-library/react';
import * as React from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-router-dom';
import { applyMiddleware, compose, Store, createStore } from 'redux';
import thunk from 'redux-thunk';
import { routerMiddleware } from 'react-router-redux';
import { createMemoryHistory } from 'history';
interface Options extends RenderOptions {
route?: string;
initialState?: any;
store?: Store;
}
const history = createMemoryHistory();
const render = (
ui: React.ReactElement,
{
route = '/',
initialState = {},
store = createStore(reducer, initialState, compose(applyMiddleware(thunk, routerMiddleware(history)))),
...options
}: Options = {},
) => {
history.push(route);
// eslint-disable-next-line react/prop-types
const Wrapper: React.FC = ({ children }) => (
<Router history={history}>
<Provider store={store}>{children}</Provider>
</Router>
);
return {
...rtlRender(ui, { wrapper: Wrapper, ...options }),
history,
store,
};
};
export * from '@testing-library/react';
export { render };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment