0

Cheers. Quick question on using @testing-library/react and creating render helpers similar to the below.

const renderWithRouter = (
    ui,
    {
        route = '/',
        history = createMemoryHistory({ initialEntries: [route] })
    } = {}
) => {
    const Wrapper = ({ children }) => (
        <Router history={history}>{children}</Router>
    );

    return {
        ...render(ui, { wrapper: Wrapper }),
        history
    };
};

const renderWithRedux = (
    ui,
    {
        initialState = {},
        reducer = {},
        store = createStore(reducer, initialState)
    } = {}
) => {
    const Wrapper = ({ children }) => (
        <Provider store={store}>{children}</Provider>
    );

    return {
        ...render(ui, { wrapper: Wrapper }),
        store
    };
};

How can I change the methods above to be composable like the following?

const render = renderWithRouter(renderWithRedux(<Component />,{...}),{...});

As far as I understand I can't just get the original UI element from within render. I'm currently stuck in thinking of another alternative. Answers/ideas much appreciated and thanks in advance.

Tom Siwik
  • 792
  • 7
  • 21

1 Answers1

0

You can create a new method to render with Router and Redux:

const renderWithRouterAndRedux = (
    ui,
    {
        route = '/',
        history = createMemoryHistory({ initialEntries: [route] }),
        initialState = {},
        reducer = {},
        store = createStore(reducer, initialState),
    } = {}
) => {
    const Wrapper = ({ children }) => (
        <Provider store={store}>
            <Router history={history}>{children}</Router>
        </Provider>
    );

    return {
        ...render(ui, { wrapper: Wrapper }),
        history,
        store,
    };
};

If you want to be more flexible I worte a little library that does that: https://github.com/Gpx/render-composer.

Giorgio Polvara - Gpx
  • 12,268
  • 5
  • 53
  • 55
  • 1
    Thanks for the answer. I'm currently using the `renderWithRouterAndRedux` version like you described. However I'm looking into a composable option (will look into composer and your library) – Tom Siwik Nov 05 '19 at 14:23