Last active
February 25, 2022 13:12
-
-
Save nottyo/3a5339193aeaa9bfed8a4fee2f16512a to your computer and use it in GitHub Desktop.
React Testing Library - Render with React Router + Redux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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