Skip to content

Instantly share code, notes, and snippets.

@AlessandraRomualdo
Last active May 19, 2023 15:31
Show Gist options
  • Save AlessandraRomualdo/915032f44cacf592f9381764258f74c7 to your computer and use it in GitHub Desktop.
Save AlessandraRomualdo/915032f44cacf592f9381764258f74c7 to your computer and use it in GitHub Desktop.
Testes no React

Testes React

Para instalar as bibliotecas

npm i @testing-library/jest-dom
npm i @testing-library/react
npm i @testing-library/user-event

Importes para os testes.

import React from 'react';
import { screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithRouterAndRedux } from './helpers/renderWith';
import App from '../App';

Funções de RenderWith utilizando Redux

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

function withRouter(component, history) {
 return (
   <Router history={ history }>
     { component }
   </Router>
 );
}

function withRedux(component, store) {
 return (
   <Provider store={ store }>
     { component }
   </Provider>
 );
}

export function renderWithRouter(
 component,
 {
   initialEntries = ['/'],
   history = createMemoryHistory({ initialEntries }),
 } = {},
) {
 return {
   ...render(withRouter(component, history)),
   history,
 };
}

export function renderWithRedux(component, options = {}) {
 const {
   initialState = {},
   store = createStore(rootReducer, initialState, applyMiddleware(thunk)),
 } = options;

 return {
   ...render(withRedux(component, store)),
   store,
 };
}

export function renderWithRouterAndRedux(component, options = {}) {
 const {
   initialEntries = ['/'],
   history = createMemoryHistory({ initialEntries }),
 } = options;

 return {
   ...renderWithRedux(withRouter(component, history), options),
   history,
 };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment