Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correção dos testes #95

Merged
merged 6 commits into from
Oct 11, 2020
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cypress/integration/Questions/answerQuestions.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { wait } = require('@testing-library/react');
import Chance from 'chance';
const { wait } = require('@testing-library/react');
const chance = new Chance();

describe('Login candidate user', () => {
Expand Down
406 changes: 406 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"docz": "^2.3.1",
"eslint-config-prettier": "^6.12.0",
"husky": "^4.3.0",
"jest-environment-jsdom-sixteen": "^1.0.3",
"lint-staged": "^10.4.0",
"prettier": "^2.1.2"
},
Expand All @@ -45,7 +46,7 @@
"build": "react-scripts build",
"build:prod": "REACT_APP_FIREBASE_ENV=prod REACT_APP_GA_ID='UA-170993659-2' npm run build",
"build:dev": "REACT_APP_FIREBASE_ENV=dev npm run build",
"test": "react-scripts test",
"test": "react-scripts test --env=jest-environment-jsdom-sixteen",
"eject": "react-scripts eject",
"lint": "eslint --ignore-path .gitignore --ext .js .",
"prettier": "prettier --ignore-path .gitignore --write \"**/*.+(js|json)\"",
Expand Down
103 changes: 70 additions & 33 deletions src/App.test.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,62 @@
import React from 'react';
import {
screen,
render,
fireEvent,
waitFor,
waitForElementToBeRemoved,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { BrowserRouter } from 'react-router-dom';
import {
firebase,
mockUnauthenticatedUser,
mockAuthenticatedUser,
} from 'tests/mockFirebaseAuth';
import firebase from 'firebase/app';

import questionsService from 'components/AnswersProvider/answersService';

import AuthenticationProvider from './AuthenticationProvider';
import * as tokenService from './customTokenService';
import App from './App';

describe('App', () => {
beforeEach(() => {
jest.clearAllMocks();
});
jest.mock('components/CityProvider/CityProvider');

beforeEach(() => {
jest.spyOn(tokenService, 'getCustomToken').mockResolvedValue('tokenzinho');
jest
.spyOn(questionsService, 'getAnsweredQuestions')
.mockResolvedValue({ 0: { answer: 'DT' }, 1: { answer: 'CT' } });
});

afterEach(() => {
jest.clearAllMocks();
});

const customRender = () =>
render(
<AuthenticationProvider>
<App />
</AuthenticationProvider>,
{ wrapper: BrowserRouter },
);

describe('App', () => {
it('renders sign in form when user is unauthenticated', async () => {
mockUnauthenticatedUser();

const { getByTestId } = render(<App />);
customRender();

fireEvent.change(getByTestId('email-input'), {
target: { value: 'any@email.com' },
});
fireEvent.change(getByTestId('password-input'), {
target: { value: 'anyPassword' },
});
fireEvent.click(getByTestId('submit-button'));
const emailInput = screen.getByLabelText('E-mail');
userEvent.type(emailInput, 'any@email.com');

await waitForElementToBeRemoved(() => getByTestId('signup-loader'));
const passwordInput = screen.getByTestId('password-input');
userEvent.type(passwordInput, 'anyPassword');

const submitButton = screen.getByRole('button', { name: 'Entrar' });
fireEvent.click(submitButton);

await waitForElementToBeRemoved(() => screen.getByTestId('submit-loader'));

expect(firebase.auth().signInWithEmailAndPassword).toBeCalledWith(
'any@email.com',
Expand All @@ -40,38 +66,49 @@ describe('App', () => {

it('renders sign up form when user is unauthenticated', async () => {
mockUnauthenticatedUser();
const { getByTestId } = render(<App />);
customRender();

fireEvent.click(getByTestId('signup-button'));
fireEvent.change(getByTestId('email-input'), {
target: { value: 'any@email.com' },
});
fireEvent.change(getByTestId('password-input'), {
target: { value: 'anyPassword' },
});
fireEvent.click(getByTestId('submit-button'));
userEvent.click(screen.getByTestId('signup-button'));

await waitForElementToBeRemoved(() => getByTestId('signup-loader'));
const emailInput = screen.getByLabelText('E-mail');
userEvent.type(emailInput, 'any@email.com');

expect(firebase.auth().createUserWithEmailAndPassword).toBeCalledWith(
'any@email.com',
'anyPassword',
const passwordInput = screen.getByLabelText('Senha');
userEvent.type(passwordInput, 'anyPassword');

const nameInput = screen.getByLabelText('Nome completo');
userEvent.type(nameInput, 'Kleber da silva');

const cityInput = screen.getByLabelText('Cidade');
userEvent.selectOptions(cityInput, 'campinas');
Comment on lines +79 to +83
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Além dos wrappers, estavam faltando estes dois campos que eram obrigatórios também


userEvent.click(screen.getByTestId('submit-button'));

await waitFor(() =>
expect(firebase.auth().createUserWithEmailAndPassword).toBeCalledWith(
'any@email.com',
'anyPassword',
),
);
});

it('renders app when user is authenticated', () => {
it('renders app when user is authenticated', async () => {
mockAuthenticatedUser();
customRender();

await waitForElementToBeRemoved(() => screen.getByTestId('page-loading'));

const { getByTestId } = render(<App />);
expect(getByTestId('app')).toBeVisible();
expect(screen.getByTestId('app')).toBeInTheDocument();
});

it('renders sign in form when users signs out', () => {
it('renders sign in form when users signs out', async () => {
mockAuthenticatedUser();
customRender();

const { getByTestId } = render(<App />);
await waitForElementToBeRemoved(() => screen.getByTestId('page-loading'));
fireEvent.click(screen.getByTestId('sidebar-burger'));

fireEvent.click(getByTestId('logout-button'));
fireEvent.click(screen.getByTestId('logout-button'));

expect(firebase.auth().signOut).toBeCalledWith();
});
Expand Down
27 changes: 12 additions & 15 deletions src/components/AnswersProvider/AnswersProvider.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { render, fireEvent, screen, wait } from '@testing-library/react';
import { render, fireEvent, screen } from '@testing-library/react';
import AnswersProvider, { AnswersContext } from './AnswersProvider';
import questionsService from './answersService';

Expand All @@ -17,22 +17,19 @@ const DataBroadcast = ({ onClick, newAnswer }) => (
</AnswersContext.Consumer>
</AnswersProvider>
);
const storedAnswers = { 0: { answer: 'DT' }, 1: { answer: 'CT' } };
beforeEach(() => {
jest
.spyOn(questionsService, 'getAnsweredQuestions')
.mockImplementation(() => Promise.resolve(storedAnswers));
});

describe('QuestionsProvider', () => {
const storedAnswers = { 0: { answer: 'DT' }, 1: { answer: 'CT' } };
beforeEach(() => {
jest
.spyOn(questionsService, 'getAnsweredQuestions')
.mockImplementation(() => Promise.resolve(storedAnswers));
});

it('should return all stored questions', async () => {
const mockedOnClick = jest.fn();
render(<DataBroadcast onClick={mockedOnClick} />);

await wait(() => {
fireEvent.click(screen.getByText('Get answers'));
});
fireEvent.click(await screen.findByRole('button', { name: 'Get answers' }));

expect(mockedOnClick).toHaveBeenCalledWith(storedAnswers);
});
Expand All @@ -42,10 +39,10 @@ describe('QuestionsProvider', () => {
const mockedOnClick = jest.fn();
render(<DataBroadcast onClick={mockedOnClick} newAnswer={newAnswer} />);

await wait(() => {
fireEvent.click(screen.getByText('Update answers'));
fireEvent.click(screen.getByText('Get answers'));
});
fireEvent.click(
await screen.findByRole('button', { name: 'Update answers' }),
);
fireEvent.click(await screen.findByRole('button', { name: 'Get answers' }));

const expectedState = {
...storedAnswers,
Expand Down
5 changes: 5 additions & 0 deletions src/components/CityProvider/__mocks__/CityProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ const CityProvider = ({ city = fakeCity, children }) => {
})),
})),
})),
options: jest.fn({
projectId: jest.fn(12345),
}),
auth: jest.fn().mockReturnThis(),
signInWithCustomToken: jest.fn().mockResolvedValue(),
};

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Creio que estes e outros mocks podem ser melhorados no futuro criando "customRenders", para cada um desses providers como neste exemplo

return (
Expand Down
11 changes: 8 additions & 3 deletions src/components/Question/Question.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const Question = ({ id, onSkip, onBack, value, user, minAnswers }) => {
const { firebase, currentUser, questionnaire, cityPath } = useContext(
CityContext,
);

const { answers, updateAnswers, getAnswersMap } = useContext(AnswersContext);
const answersLength = Object.values(answers).length;

Expand Down Expand Up @@ -73,7 +74,7 @@ const Question = ({ id, onSkip, onBack, value, user, minAnswers }) => {
const handleSubmit = (event) => {
event.preventDefault();

if (!event.target.answer.value) {
if (!event?.target?.answer?.value) {
setErrorMessage('Escolha uma opção.');
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
Expand All @@ -99,12 +100,16 @@ const Question = ({ id, onSkip, onBack, value, user, minAnswers }) => {

const handlePrevious = () => {
setErrorMessage(null);
onBack();
if (onBack) {
onBack();
}
};

const handleSkip = () => {
setErrorMessage(null);
onSkip();
if (onSkip) {
onSkip();
}
};

return (
Expand Down
35 changes: 25 additions & 10 deletions src/components/Question/Question.test.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,41 @@
import React from 'react';
import { render, screen, wait } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';

import Question from './Question';

import { ROLE_VOTER } from 'constants/userRoles';

import CityProvider from 'components/CityProvider/CityProvider';
import AnswersProvider from 'components/AnswersProvider/AnswersProvider';
import questionsService from 'components/AnswersProvider/answersService';

const storedAnswers = { 0: { answer: 'DT' }, 1: { answer: 'CT' } };
beforeEach(() => {
jest
.spyOn(questionsService, 'getAnsweredQuestions')
.mockImplementation(() => Promise.resolve(storedAnswers));
});

jest.mock('components/CityProvider/CityProvider');

describe('Question', () => {
it('renders the provided question', async () => {
const mockSave = jest.fn();
const mockedUser = { role: ROLE_VOTER };

render(
<CityProvider>
<Question id={1} onSave={mockSave} />
</CityProvider>,
<BrowserRouter>
<CityProvider>
<Question user={mockedUser} id={1} />
</CityProvider>
</BrowserRouter>,
{
wrapper: AnswersProvider,
},
);

expect(screen.getByText('Any question title 1')).toBeVisible();
userEvent.click(screen.getByText('Discordo'));
userEvent.click(screen.getByText('Salvar'));
await wait(() => expect(mockSave).toBeCalled());
expect(await screen.findByText('Any question title 2')).toBeInTheDocument();

expect(screen.getByLabelText('Discordo')).toBeInTheDocument();
});
});
5 changes: 4 additions & 1 deletion src/components/Sidebar/Navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ const Navigation = ({ user }) => {
return (
<div>
<StyledBurger
data-testid="navigation-burger"
aria-label="Abrir ou fechar menu"
open={true}
onClick={toggleSidebar}
Expand Down Expand Up @@ -86,7 +87,9 @@ const Navigation = ({ user }) => {
</Ul>
<Divider />
<QuestionsBoard user={user} />
<StyledLogout onClick={handleLogout}>Sair</StyledLogout>
<StyledLogout data-testid="logout-button" onClick={handleLogout}>
Sair
</StyledLogout>
</div>
);
};
Expand Down
6 changes: 5 additions & 1 deletion src/components/Sidebar/Sidebar.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ export default function Sidebar({ user }) {

return (
<SidebarProvider isOpen={isOpen} toggleSidebar={toggleSidebar}>
<StyledBurger aria-label="Abrir ou fechar menu" onClick={toggleSidebar}>
<StyledBurger
data-testid="sidebar-burger"
aria-label="Abrir ou fechar menu"
onClick={toggleSidebar}
>
<span />
<span />
<span />
Expand Down
6 changes: 5 additions & 1 deletion src/components/User/SignInForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ const SignInForm = ({ updateErrorMessage, setShowForgotPasswordForm }) => {
disabled={loading}
data-testid="submit-button"
>
{loading ? <Spinner color="light" size="sm" /> : 'Entrar'}
{loading ? (
<Spinner data-testid="submit-loader" color="light" size="sm" />
) : (
'Entrar'
)}
</Button>
</Form>
<StyledSpan>
Expand Down
2 changes: 1 addition & 1 deletion src/components/User/SignUpForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ const SignUpForm = ({ onBackClick, user }) => {
<form onSubmit={handleSubmit(onSubmit)}>
<Row>
<Col>
{loading && <Spinner color="primary" />}
{loading && <Spinner data-testid="signup-loader" color="primary" />}
{errorMessage && <Alert color="danger">{errorMessage}</Alert>}

<FormGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/components/molecules/PageLoading/PageLoading.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { faSpinner } from '@fortawesome/free-solid-svg-icons';

const PageLoading = () => {
return (
<Container fluid className="text-primary">
<Container fluid className="text-primary" data-testid="page-loading">
<Row className="vh-100">
<Col sm="12" className="text-center my-auto">
<h1 className="display-4">
Expand Down
6 changes: 5 additions & 1 deletion src/pages/Home.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ const HomePage = () => {
const name = currentUser.displayName;

return (
<Container className="py-4" style={{ lineHeight: '20px' }}>
<Container
data-testid="app"
className="py-4"
style={{ lineHeight: '20px' }}
>
{!enableRanking && <Modal name={name} />}

<StyledUserName className="mt-3">Olá, {name},</StyledUserName>
Expand Down
Loading