Created
September 9, 2020 03:24
-
-
Save fadi-george/1a7cc0badb6e414d64413435022dc6a4 to your computer and use it in GitHub Desktop.
Test util helper for rendering components with various context/providers (e.g. 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 { Provider } from 'react-redux'; | |
import { Router } from 'react-router-dom'; | |
import { SWRConfig } from 'swr'; | |
import { MuiThemeProvider } from '@material-ui/core'; | |
import { SnackbarProvider } from 'notistack'; | |
import { MuiPickersUtilsProvider } from '@material-ui/pickers'; | |
export const Providers = ({ | |
children, | |
history, | |
socket = null, | |
store = null, | |
}: any) => { | |
let Wrapper = ( | |
<SWRConfig value={{ dedupingInterval: 0 }}> | |
<MuiThemeProvider theme={muiTheme}> | |
<MuiPickersUtilsProvider utils={MomentUtils}> | |
<SnackbarProvider>{children}</SnackbarProvider> | |
</MuiPickersUtilsProvider> | |
</MuiThemeProvider> | |
</SWRConfig> | |
); | |
if (socket) { | |
Wrapper = ( | |
<SocketContext.Provider value={{ socket }}> | |
{Wrapper} | |
</SocketContext.Provider> | |
); | |
} | |
if (history) { | |
Wrapper = <Router history={history}>{Wrapper}</Router>; | |
} | |
if (store) { | |
Wrapper = <Provider store={mockStore(store)}>{Wrapper}</Provider>; | |
} | |
return Wrapper; | |
}; | |
interface ProviderOptions extends RenderOptions { | |
store?: object; | |
socket?: object; | |
initialEntries?: Array<string>; | |
} | |
export const renderWithProviders = ( | |
ui: React.ReactElement, | |
options: ProviderOptions = {}, | |
) => { | |
const { initialEntries, socket, store, ...rest } = options; | |
const history = initialEntries | |
? createMemoryHistory({ initialEntries }) | |
: null; | |
const rtl = render(ui, { | |
wrapper: ({ children }) => ( | |
<Providers | |
history={history} | |
// initialEntries={initialEntries} | |
socket={socket} | |
store={store} | |
> | |
{children} | |
</Providers> | |
), | |
...rest, | |
}); | |
return { | |
...rtl, | |
rerender: (ui: React.ReactElement, rerenderOptions?: ProviderOptions) => | |
renderWithProviders(ui, { | |
container: rtl.container, | |
...options, | |
...rerenderOptions, | |
}), | |
history, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment