Skip to content

Instantly share code, notes, and snippets.

@gabrielh-silvestre
Last active June 21, 2022 19:36
Show Gist options
  • Save gabrielh-silvestre/7e1b30a84005798627e744ccbf9b3907 to your computer and use it in GitHub Desktop.
Save gabrielh-silvestre/7e1b30a84005798627e744ccbf9b3907 to your computer and use it in GitHub Desktop.
Test helpers for RTL
import React, { createContext } from 'react';
import { render } from '@testing-library/react';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import { Router } from 'react-router';
import { createMemoryHistory } from 'history';
export const renderWithRouter = (component) => {
const history = createMemoryHistory();
return {
...render(<Router history={ createMemoryHistory() }>{component}</Router>),
history,
};
};
export const renderWithRedux = (
component,
{
initialState,
store = createStore(rootReducers, initialState, applyMiddleware(thunk)),
} = {},
) => ({
...render(<Provider store={ store }>{component}</Provider>),
store,
});
export const renderWithContext = (
component,
{
initialValue,
Context = createContext(initialValue),
},
) => ({
...render(
<Context.Provider value={ initialValue }>
{component}
</Context.Provider>,
),
Context,
});
export const renderWithRouterAndRedux = (
component,
{
initialState = {},
store = createStore(rootReducers, initialState, applyMiddleware(thunk)),
initialEntries = ['/'],
history = createMemoryHistory({ initialEntries }),
} = {},
) => ({
...render(
<Router history={ history }>
<Provider store={ store }>{component}</Provider>
</Router>,
),
history,
store,
});
export const renderWithReduxAndContext = (
component,
{
initialState = {},
store = createStore(rootReducers, initialState, applyMiddleware(thunk)),
initialValue,
Context = createContext(initialValue),
} = {},
) => ({
...render(
<Provider store={ store }>
<Context.Provider value={ initialValue }>{component}</Context.Provider>
</Provider>,
),
store,
Context,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment