Skip to content

Instantly share code, notes, and snippets.

@AlessandraRomualdo
Created June 7, 2023 14:40
Show Gist options
  • Save AlessandraRomualdo/9a3d0fb2cb1e493d1aadb3fc7f14dc78 to your computer and use it in GitHub Desktop.
Save AlessandraRomualdo/9a3d0fb2cb1e493d1aadb3fc7f14dc78 to your computer and use it in GitHub Desktop.
Testes React e Context

Testes com Context no React.

Inportações e renderWithRouterAndContext

import React from 'react';
import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { screen, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Provider from '../context/myProvider';
import App from '../App';

const renderWithRouterAndContext = (component, path = '/') => {
  const history = createMemoryHistory({ initialEntries: [path] });
  return ({
    ...render(
      <Provider>
        <Router history={ history }>
          {component}
        </Router>
      </Provider>,
    ),
    history,
  });
};

Teste de LocalStorage

it('Testa caso LocalStorage', async () => {
    const email = { email: 'outro@trybe.com' };

    localStorage.setItem('user', JSON.stringify(email));

    jest.spyOn(Object.getPrototypeOf(global.localStorage), 'getItem')
      .mockReturnValue(JSON.stringify(email));

    renderWithRouterAndContext(<App />, '/animal');

    await waitFor(() => expect(screen.getByText('DOGS VS CATS')).toBeInTheDocument());

    expect(global.alert).toHaveBeenCalledTimes(1);

    screen.getByText('outro@trybe.com');

    expect(localStorage.getItem).toHaveBeenCalled();
  });

  it('Testa caso não tenha LocalStorage', async () => {
    jest.spyOn(Object.getPrototypeOf(global.localStorage), 'getItem')
      .mockReturnValue(JSON.stringify(''));

    renderWithRouterAndContext(<App />, '/animal');

    await waitFor(() => expect(screen.getByText('DOGS VS CATS')).toBeInTheDocument());

    expect(global.alert).toHaveBeenCalledTimes(1);

    screen.getByText('não existe email');

    expect(localStorage.getItem).toHaveBeenCalled();
  });

Teste de Caso erro de fetch

 it('Testa caso de erro', () => {
  jest.spyOn(global, 'fetch').mockRejectedValue(new Error('DEU RUIM'));
  renderWithRouterAndContext(<App />, '/animal');

  expect(requestApi()).rejects.toThrow(new Error('Endpoint is required'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment