Skip to content

Commit

Permalink
Add unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lucianogorza committed Mar 5, 2024
1 parent a0034ae commit 7a8d06d
Show file tree
Hide file tree
Showing 16 changed files with 400 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react-hooks';
import { useGetTotalAgents } from './agents';
import { getAgentsService } from '../services';

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { renderHook } from '@testing-library/react-hooks';
import { getTasks } from '../services';
import { useGetUpgradeTasks } from './upgrade-tasks';
import { API_NAME_TASK_STATUS } from '../../../../common/constants';

jest.mock('../services', () => ({
getTasks: jest.fn(),
}));

jest.useFakeTimers();
jest.spyOn(global, 'clearInterval');

describe('useGetUpgradeTasks hook', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('should fetch initial data without any error', async () => {
const mockGetTasks = jest.requireMock('../services').getTasks;
mockGetTasks.mockImplementation(async ({ status }) => {
if (status === API_NAME_TASK_STATUS.IN_PROGRESS) {
return { total_affected_items: 5 };
}
return { total_affected_items: 2 };
});

const { result, waitForNextUpdate } = renderHook(() =>
useGetUpgradeTasks(false),
);

expect(result.current.getInProgressIsLoading).toBe(true);
expect(result.current.totalInProgressTasks).toBeUndefined();
expect(result.current.getInProgressError).toBeUndefined();

expect(result.current.getErrorIsLoading).toBe(true);
expect(result.current.totalErrorUpgradeTasks).toBeUndefined();
expect(result.current.getErrorTasksError).toBeUndefined();

await waitForNextUpdate();
jest.advanceTimersByTime(500);

expect(result.current.getInProgressIsLoading).toBe(false);
expect(result.current.totalInProgressTasks).toBe(5);
expect(result.current.getInProgressError).toBeUndefined();

jest.advanceTimersByTime(500);

expect(result.current.getErrorIsLoading).toBe(false);
expect(result.current.totalErrorUpgradeTasks).toBe(2);
expect(result.current.getErrorTasksError).toBeUndefined();
});

it('should clear interval when totalInProgressTasks is 0', async () => {
const mockGetTasks = jest.requireMock('../services').getTasks;
mockGetTasks.mockResolvedValue({ total_affected_items: 0 });

const { waitForNextUpdate } = renderHook(() => useGetUpgradeTasks(false));

await waitForNextUpdate();
jest.advanceTimersByTime(500);

expect(clearInterval).toHaveBeenCalledTimes(2);
});

it('should handle error while fetching data', async () => {
const mockErrorMessage = 'Some error occurred';
(getTasks as jest.Mock).mockRejectedValue(mockErrorMessage);

const { result, waitForNextUpdate } = renderHook(() =>
useGetUpgradeTasks(0),
);

expect(result.current.getInProgressIsLoading).toBeTruthy();
await waitForNextUpdate();
expect(result.current.getInProgressError).toBe(mockErrorMessage);
expect(result.current.getInProgressIsLoading).toBeFalsy();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ export const useGetUpgradeTasks = reload => {
getInProgressIsLoading,
totalInProgressTasks,
getInProgressError,
totalErrorUpgradeTasks: 5,
getErrorIsLoading,
totalErrorUpgradeTasks,
getErrorTasksError,
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { API_NAME_TASK_STATUS } from '../../../../common/constants';
import { WzRequest } from '../../../react-services/wz-request';
import { getTasks } from './get-tasks';

jest.mock('../../../react-services/wz-request', () => ({
WzRequest: {
apiReq: jest.fn(),
},
}));

describe('getTasks', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('should retrieve tasks', async () => {
(WzRequest.apiReq as jest.Mock).mockResolvedValue({
data: {
data: {
affected_items: [
{
task_id: 1,
agent_id: '001',
status: API_NAME_TASK_STATUS.DONE,
command: 'upgrade',
},
{
task_id: 2,
agent_id: '002',
status: API_NAME_TASK_STATUS.DONE,
command: 'upgrade',
},
],
total_affected_items: 2,
failed_items: [],
total_failed_items: 0,
},
error: 0,
message: 'Success',
},
});

const result = await getTasks({
status: API_NAME_TASK_STATUS.DONE,
command: 'upgrade',
limit: 10,
});

expect(WzRequest.apiReq).toHaveBeenCalledWith('GET', '/tasks/status', {
params: {
status: API_NAME_TASK_STATUS.DONE,
command: 'upgrade',
limit: 10,
offset: 0,
q: undefined,
wait_for_complete: true,
},
});

expect(result).toEqual({
affected_items: [
{
task_id: 1,
agent_id: '001',
status: API_NAME_TASK_STATUS.DONE,
command: 'upgrade',
},
{
task_id: 2,
agent_id: '002',
status: API_NAME_TASK_STATUS.DONE,
command: 'upgrade',
},
],
total_affected_items: 2,
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ exports[`AgentsTable component Renders correctly to match the snapshot 1`] = `
<div
class="euiFlexGroup euiFlexGroup--gutterLarge euiFlexGroup--alignItemsCenter euiFlexGroup--directionRow euiFlexGroup--wrap"
>
<div
class="euiFlexItem euiFlexItem--flexGrowZero"
/>
<div
class="euiFlexItem euiFlexItem--flexGrowZero"
>
Expand Down Expand Up @@ -562,7 +565,7 @@ exports[`AgentsTable component Renders correctly to match the snapshot 1`] = `
data-test-subj="tableHeaderCell_version_6"
role="columnheader"
scope="col"
style="width:10%"
style="width:100px"
>
<button
class="euiTableHeaderButton"
Expand Down Expand Up @@ -698,6 +701,9 @@ exports[`AgentsTable component Renders correctly to match the snapshot with cust
<div
class="euiFlexGroup euiFlexGroup--gutterLarge euiFlexGroup--alignItemsCenter euiFlexGroup--directionRow euiFlexGroup--wrap"
>
<div
class="euiFlexItem euiFlexItem--flexGrowZero"
/>
<div
class="euiFlexItem euiFlexItem--flexGrowZero"
>
Expand Down Expand Up @@ -1149,7 +1155,7 @@ exports[`AgentsTable component Renders correctly to match the snapshot with cust
data-test-subj="tableHeaderCell_version_3"
role="columnheader"
scope="col"
style="width:10%"
style="width:100px"
>
<button
class="euiTableHeaderButton"
Expand Down Expand Up @@ -1309,6 +1315,9 @@ exports[`AgentsTable component Renders correctly to match the snapshot with no p
<div
class="euiFlexGroup euiFlexGroup--gutterLarge euiFlexGroup--alignItemsCenter euiFlexGroup--directionRow euiFlexGroup--wrap"
>
<div
class="euiFlexItem euiFlexItem--flexGrowZero"
/>
<div
class="euiFlexItem euiFlexItem--flexGrowZero"
>
Expand Down Expand Up @@ -1832,7 +1841,7 @@ exports[`AgentsTable component Renders correctly to match the snapshot with no p
data-test-subj="tableHeaderCell_version_6"
role="columnheader"
scope="col"
style="width:10%"
style="width:100px"
>
<button
class="euiTableHeaderButton"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`UpgradeAgentModal component should return the component 1`] = `
<div
aria-hidden="true"
data-aria-hidden="true"
/>
`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import React from 'react';
import { render, fireEvent, waitFor, act } from '@testing-library/react';
import '@testing-library/jest-dom';
import { UpgradeAgentModal } from './upgrade-agent-modal';

jest.mock('../../services', () => ({
upgradeAgentsService: jest.fn(),
}));

jest.mock('../../../../react-services/common-services', () => ({
getErrorOrchestrator: () => ({
handleError: () => {},
}),
}));

describe('UpgradeAgentModal component', () => {
test('should return the component', async () => {
const { container, getByText, getByRole } = render(
<UpgradeAgentModal
agent={{
id: '001',
name: 'agent1',
group: ['default'],
}}
onClose={() => {}}
reloadAgents={() => {}}
/>,
);

expect(container).toMatchSnapshot();

const agentName = getByText('Upgrade agent agent1?');
expect(agentName).toBeInTheDocument();

const saveButton = getByRole('button', { name: 'Upgrade' });
expect(saveButton).toBeInTheDocument();

const cancelButton = getByRole('button', { name: 'Cancel' });
expect(cancelButton).toBeInTheDocument();
});

test('should send to upgrade', async () => {
const { getByText, getByRole } = render(
<UpgradeAgentModal
agent={{
id: '001',
name: 'agent1',
group: ['default'],
}}
onClose={() => {}}
reloadAgents={() => {}}
/>,
);

const saveButton = getByRole('button', { name: 'Upgrade' });
expect(saveButton).toBeInTheDocument();

act(() => {
fireEvent.click(saveButton);
});
});
});
Loading

0 comments on commit 7a8d06d

Please sign in to comment.