Skip to content

Commit

Permalink
Merge pull request #17 from fonteeboa/add-test
Browse files Browse the repository at this point in the history
Jest: adicionando testes
  • Loading branch information
fonteeboa authored Dec 18, 2023
2 parents 0cb071d + ef2d98a commit e6a6b51
Show file tree
Hide file tree
Showing 20 changed files with 472 additions and 74 deletions.
8 changes: 4 additions & 4 deletions src/components/baseComponents/inputField/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,18 @@ export const InputField: React.FC<IInputField> = ({ name, type, icon, label, onC
*
* @param {any} type - The type of icon to retrieve.
* @return {any} The corresponding icon component.
*/
*/
const getIcon = (type: any) => {
let icons: any;
switch (type) {
case 'email':
icons = <Mail />
icons = <Mail data-testid={'iconMail'} />
break;
case 'password':
icons = <LockClosed />
icons = <LockClosed data-testid={'iconLockClosed'} />
break;
case 'text':
icons = <User />
icons = <User data-testid={'iconUser'} />
break;
default:
icons = "";
Expand Down
1 change: 0 additions & 1 deletion src/components/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

// Exportando componentes base e seus tipos, se houver
export {
BulkActionsDropdown,
Expand Down
9 changes: 5 additions & 4 deletions src/components/layout/sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,19 @@ function renderSubMenu(subMenu: SubMenuItem[]) {

if (subSubMenu && subSubMenu.length > 0) {
return (
<SubMenu key={'subMenu'+ index + 'subMenu'} title={label} icon={itemIcon}>
<SubMenu key={'subMenu2'+ index} title={label} icon={itemIcon} data-testid={index + '-' + label}>
{renderSubMenu(subSubMenu)}
</SubMenu>
);
} else if (route) {
return (
<Menu.Item key={'MenuItem'+ index} icon={itemIcon}>
<Menu.Item key={'MenuItem'+ index} icon={itemIcon} data-testid={index + '-' + label}>
{external ? <a href={route} target="_blank" rel="noopener noreferrer"> { label } </a> : linkComponent}
</Menu.Item>
);
} else {
return (
<Menu.Item key={'MenuItem'+index} icon={itemIcon}>
<Menu.Item key={'MenuItem'+index} icon={itemIcon} data-testid={index + '-' + label}>
{label}
</Menu.Item>
);
Expand All @@ -46,6 +46,7 @@ function renderMenuItem(item: MenuItem, index: number) {
return (
<SubMenu
key={'SubMenu'+index}
data-testid={index + '-' + item.label}
title={item.label}
icon={
item.icon ? (
Expand All @@ -62,7 +63,7 @@ function renderMenuItem(item: MenuItem, index: number) {
);
} else {
return (
<Menu.Item key={'Menu'+index} icon={item.icon ? <FontAwesomeIcon icon={item.icon as IconProp} /> : null}>
<Menu.Item key={'Menu'+index} icon={item.icon ? <FontAwesomeIcon icon={item.icon as IconProp} /> : null} data-testid={index + '-' + item.label}>
{item.label}
</Menu.Item>
);
Expand Down
4 changes: 4 additions & 0 deletions src/test/mock/bulkActions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const mockActions = [
{ name: 'Action 1', handler: jest.fn(), activeAction: true },
{ name: 'Dangerous Action', handler: jest.fn(), type: 'danger', confirmMessage: 'Are you sure?', activeAction: true }
];
3 changes: 3 additions & 0 deletions src/test/mock/customTable.js → src/test/mock/grid.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
export const mockDeleteAction = jest.fn();
export const mockOpenModalAction = jest.fn();

// Mock das colunas e dados de exemplo
export const columns = [
{
Expand Down
10 changes: 0 additions & 10 deletions src/test/mock/inputField.js

This file was deleted.

31 changes: 31 additions & 0 deletions src/test/mock/modal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export const mockFieldsDoubleLines = [
{ label: 'ID', name: 'ID', type: 'hidden' },
{ name: "doublelines",
doublelines: [
{ label: 'common.name', name: 'name' },
{ label: 'common.key', name: 'key' },
]
},
];

export const mockFields = [
{ label: 'common.name2', name: 'Name2' },
];

export const mockCloseModal = jest.fn();

export const mockOnSave = jest.fn();

export const tableContentsData = [
{
fields: mockFieldsDoubleLines,
contentLabel: 'Tab 1 Content',
name: 'Tab 1',
},
{
fields: mockFields,
contentLabel: 'Tab 2 Content',
name: 'Tab 2',
},
// Pode adicionar mais elementos de acordo com a estrutura definida
];
51 changes: 51 additions & 0 deletions src/test/src/Modal.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React from 'react';
import { render, fireEvent, screen, waitFor} from '@testing-library/react';
import '@testing-library/jest-dom';
import Modal from 'react-modal';
import { ModalFormHandler } from '../../components/baseLayouts/modals/modalFormHandler';
import { mockCloseModal, mockOnSave, mockFields, mockFieldsDoubleLines } from '../mock/modal';
import { setMatchMediaMock } from '../mock/matchMedia';

setMatchMediaMock();
Modal.setAppElement('*');

const makeRender = (fields) => {
render(
<ModalFormHandler
closeModal={mockCloseModal}
onSave={mockOnSave}
fields={fields}
contentLabel="Test Modal"
currentItem={{}}
/>
);
}

describe('Modal render', () => {

it('deve renderizar o modal mockFields', () => {
makeRender(mockFields);
expect(screen.getByText('common.name2')).toBeInTheDocument();
expect(screen.getByText('common.cancel')).toBeInTheDocument();
expect(screen.getByText('common.save')).toBeInTheDocument();
});

it('deve renderizar o modal mockFieldsDoubleLines', () => {
makeRender(mockFieldsDoubleLines);
expect(screen.getByText('common.name')).toBeInTheDocument();
expect(screen.getByText('common.key')).toBeInTheDocument();
expect(screen.getByText('common.cancel')).toBeInTheDocument();
expect(screen.getByText('common.save')).toBeInTheDocument();
});

});

describe('Modal functions', () => {

it('deve chamar closeModal ao clicar no botão cancelar', () => {
makeRender(mockFields);
fireEvent.click(screen.getByText('common.cancel'));
expect(mockCloseModal).toHaveBeenCalled();
});

})
51 changes: 43 additions & 8 deletions src/test/src/bulkActionsDropdown.test.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,53 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { BulkActionsDropdown } from '../../components';
import { render, fireEvent, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { BulkActionsDropdown } from '../../components';
import { Menu, Popconfirm } from 'antd';
import { mockActions } from '../mock/bulkActions';

const makeRender = (actions = []) => {
render(
<BulkActionsDropdown actions={actions} />
);
const makeRender = (actions = []) => {
render(<BulkActionsDropdown actions={actions} />);
}

describe('BulkActionsDropdown', () => {
// Teste para verificar se o componente renderiza corretamente
it('renders correctly', () => {

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

it('deve renderizar o botao', () => {
makeRender()
expect(screen.getByRole('button')).toBeInTheDocument();
});

it('deve renderizar e abrir o menu dropdown', () => {
render(<BulkActionsDropdown actions={mockActions} />);

const button = screen.getByRole('button');
fireEvent.click(button);

expect(screen.getByText('Action 1')).toBeInTheDocument();
expect(screen.getByText('Dangerous Action')).toBeInTheDocument();
});

it('deve chamar a ação do handler ao clicar em um item do menu', () => {
render(<BulkActionsDropdown actions={mockActions} />);

fireEvent.click(screen.getByRole('button'));
fireEvent.click(screen.getByText('Action 1'));

expect(mockActions[0].handler).toHaveBeenCalled();
});

it('deve exibir o popconfirm e chamar o handler para ação perigosa', () => {
render(<BulkActionsDropdown actions={mockActions} />);

fireEvent.click(screen.getByRole('button'));
fireEvent.click(screen.getByText('Dangerous Action'));

const popconfirmYesButton = screen.getByText('common.ok');
fireEvent.click(popconfirmYesButton);

expect(mockActions[1].handler).toHaveBeenCalled();
});
});
20 changes: 11 additions & 9 deletions src/test/src/button.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import { render, fireEvent } from '@testing-library/react';
import {Button} from '../../components';
import { buttonProps, onClickMock } from '../mock/button';

test('Renderiza o componente Button corretamente', () => {
const { getByText } = render(<Button {...buttonProps} />);
// Verifique se o componente Button foi renderizado com os valores corretos
expect(getByText('Click me')).toBeInTheDocument();

// Simule um clique no botão e verifique se o manipulador de clique é chamado
fireEvent.click(getByText('Click me'));
expect(onClickMock).toHaveBeenCalledTimes(1);
});
describe('Button', () => {
it('Renderiza o componente Button corretamente', () => {
const { getByText } = render(<Button {...buttonProps} />);
// Verifique se o componente Button foi renderizado com os valores corretos
expect(getByText('Click me')).toBeInTheDocument();

// Simule um clique no botão e verifique se o manipulador de clique é chamado
fireEvent.click(getByText('Click me'));
expect(onClickMock).toHaveBeenCalledTimes(1);
});
})
39 changes: 39 additions & 0 deletions src/test/src/downloadScreenLoading.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import DownloadScreenLoading from '../../components/layout/downloadScreenLoading';

describe('DownloadScreenLoading', () => {
const mockT = jest.fn().mockImplementation((key) => key);

it('deve exibir o carregador quando loading é verdadeiro', () => {
render(<DownloadScreenLoading loading={true} t={mockT} />);
// Verifique se o carregador foi renderizado
expect(screen.getByLabelText('blocks-loading')).toBeInTheDocument();
});

it('deve exibir o resultado de aviso e botão de recarga quando loading é falso', () => {
render(<DownloadScreenLoading loading={false} t={mockT} />);
// Verifique se o resultado de aviso foi renderizado
expect(screen.getByText('common.unavaible')).toBeInTheDocument();
expect(screen.getByText('common.reload.page')).toBeInTheDocument();
});

it('deve chamar window.location.reload ao clicar no botão de recarga', () => {
delete window.location;
window.location = { reload: jest.fn() };
render(<DownloadScreenLoading loading={false} t={mockT} />);
// Clique no botão de recarga
fireEvent.click(screen.getByText('common.reload.page'));
expect(window.location.reload).toHaveBeenCalled();
});

it('deve exibir o botão de download quando downloadUrl é fornecido', () => {
render(<DownloadScreenLoading loading={false} downloadUrl="http://download.com" t={mockT} />);
// Verifique se o botão de download foi renderizado
expect(screen.getByText('module.info.download')).toBeInTheDocument();
// Verifique se o botão de download possui o atributo href correto
const downloadButton = screen.getByText('module.download');
expect(downloadButton.closest('a')).toHaveAttribute('href', 'http://download.com');
});

});
23 changes: 0 additions & 23 deletions src/test/src/dynamicTable.test.js

This file was deleted.

52 changes: 52 additions & 0 deletions src/test/src/grid.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { Grid } from '../../components';
import '../../i18n';
import { dataSource, columns, bulkAction, mockDeleteAction, mockOpenModalAction } from '../mock/grid';
import { setMatchMediaMock } from '../mock/matchMedia';

setMatchMediaMock();

const makeRender = (rowSelectionBoolean = false) => {
render(
<Grid
pageTitle="Tabela de Usuários"
dataSource={dataSource}
columns={columns}
bulkAction={bulkAction}
deleteAction={mockDeleteAction}
openModalAction={mockOpenModalAction}
rowSelectionBoolean={rowSelectionBoolean}
/>
);
}
describe('Grid', () => {

it('Renderiza o componente Grid corretamente', () => {
makeRender();
// Verifique a renderização do título da tabela
expect(screen.getByText('Tabela de Usuários')).toBeInTheDocument();
});

it('deve selecionar linhas e atualizar o botão de ação em massa', () => {
makeRender(true);

const checkboxes = screen.getAllByRole('checkbox');
fireEvent.click(checkboxes[0]); // Selecionar todas as linhas

expect(checkboxes[1]).toBeChecked(); // Verifica se a primeira linha está selecionada
expect(checkboxes[2]).toBeChecked();
});

it('deve chamar deleteAction com linhas selecionadas', () => {
makeRender(true)
const checkboxes = screen.getAllByRole('checkbox');
fireEvent.click(checkboxes[0]);
fireEvent.click(screen.getAllByRole('button')[0]);
fireEvent.click(screen.getByText('common.delete.select'));
expect(mockDeleteAction).toHaveBeenCalledWith(dataSource);
});

});


Loading

0 comments on commit e6a6b51

Please sign in to comment.