Skip to content

Instantly share code, notes, and snippets.

@ANDREHORMAN1994
Last active September 9, 2023 17:40
Show Gist options
  • Save ANDREHORMAN1994/b68bdd7bcc96a3fb797ecfcb4f62c3ba to your computer and use it in GitHub Desktop.
Save ANDREHORMAN1994/b68bdd7bcc96a3fb797ecfcb4f62c3ba to your computer and use it in GitHub Desktop.
Funções genéricas do RTL

RenderWithRouter v5

import React from 'react';
import { createMemoryHistory } from 'history';
import { Router } from 'react-router-dom';
import { render } from '@testing-library/react';

function renderWithRouter(component, path = '/') {
  const history = createMemoryHistory({ initialEntries: [path] });
  const result = {
    ...render(
      <Router history={ history }>
        { component }
      </Router>,
    ),
    history,
  };

  return result;
}

export default renderWithRouter;

RenderWithRedux

import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { render } from '@testing-library/react';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';

import { reducer } from './redux/reducers/reducer'

function renderWithRedux() {
  component,
  {
    initialState,
    store = createStore(combineReducers({ counterReducer }), initialState),
  } = {}
) => ({
  ...render(<Provider store={store}>{component}</Provider>),
  store, // função auxiliar retornando a store
};

export default renderWithRedux;

RenderWithRouterAndRedux v5

import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { render } from '@testing-library/react';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';

import { reducer } from './redux/reducers/reducer'

const renderWithRouterAndRedux = (
  component,
  {
    initialState = {},
    store = createStore(reducer, initialState, applyMiddleware(thunk)),
    initialEntries = ['/'],
    history = createMemoryHistory({ initialEntries }),
  } = {},
) => ({
  ...render(
    <Router history={ history }>
      <Provider store={ store }>
        {component}
      </Provider>
    </Router>,
  ),
  store,
  history,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment