Skip to content

Commit

Permalink
OHRI-2078 Add unit tests for encounter list in commons lib (#1824)
Browse files Browse the repository at this point in the history
* OHRI-2078 Add unit tests for encounter list in commons lib

* fixed linting issues

* code review
  • Loading branch information
CynthiaKamau authored Mar 27, 2024
1 parent f9b8651 commit 28ee703
Show file tree
Hide file tree
Showing 19 changed files with 1,398 additions and 52 deletions.
1,252 changes: 1,252 additions & 0 deletions __mocks__/encounter-list.mock.tsx

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ interface TableProps {
}

export const OTable: React.FC<TableProps> = ({ tableHeaders, tableRows }) => {

return (
<TableContainer>
<DataTable rows={tableRows} headers={tableHeaders} isSortable={true} size="md">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,7 @@ export const EncounterList: React.FC<EncounterListProps> = ({
const { isDead } = usePatientDeathStatus(patientUuid);
const formNames = useMemo(() => formList.map((form) => form.name), []);
const { formsJson, isLoading: isLoadingFormsJson } = useFormsJson(formNames);
const {
encounters,
isLoading: isLoadingEncounters,
onFormSave,
} = useEncounterRows(patientUuid, encounterType, filter);
const { encounters, isLoading, onFormSave } = useEncounterRows(patientUuid, encounterType, filter);
const { moduleName, workspaceWindowSize, displayText, hideFormLauncher } = launchOptions;

const defaultActions = useMemo(
Expand Down Expand Up @@ -163,7 +159,7 @@ export const EncounterList: React.FC<EncounterListProps> = ({
};
// process columns
columns.forEach((column) => {
let val = column.getValue(encounter);
let val = column?.getValue(encounter);
if (column.link) {
val = (
<Link
Expand All @@ -187,6 +183,7 @@ export const EncounterList: React.FC<EncounterListProps> = ({
<OverflowMenu flipped className={styles.flippedOverflowMenu}>
{actions.map((actionItem, index) => (
<OverflowMenuItem
index={index}
itemText={actionItem.label}
onClick={(e) => {
e.preventDefault();
Expand Down Expand Up @@ -246,7 +243,7 @@ export const EncounterList: React.FC<EncounterListProps> = ({
</Button>
);
} else if (forms.length && !(hideFormLauncher ?? isDead)) {
return (
return () => (
<OHRIFormLauncherWithIntent
formJsonList={forms}
launchForm={(formJson, intent) =>
Expand All @@ -266,17 +263,21 @@ export const EncounterList: React.FC<EncounterListProps> = ({
/>
);
}
return null;
}, [forms, hideFormLauncher, isDead, displayText, moduleName, workspaceWindowSize, onFormSave, patientUuid]);

if (isLoading === true || isLoadingForms === true || isLoadingFormsJson === true) {
return <DataTableSkeleton rowCount={5} />;
}

return (
<>
{isLoadingEncounters || isLoadingForms ? (
<DataTableSkeleton rowCount={5} />
) : encounters.length > 0 ? (
{paginatedRows?.length > 0 || encounters.length > 0 ? (
<>
<div className={styles.widgetContainer}>
<div className={styles.widgetHeaderContainer}>
<h4 className={`${styles.productiveHeading03} ${styles.text02}`}>{headerTitle}</h4>
{/* @ts-ignore */}
{!(hideFormLauncher ?? isDead) && <div className={styles.toggleButtons}>{formLauncher}</div>}
</div>
<OTable tableHeaders={headers} tableRows={paginatedRows} />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import '@testing-library/jest-dom';
import React from 'react';
import { act, render, screen } from '@testing-library/react';
import { EncounterList } from './encounter-list.component';
import { openmrsFetch, usePagination } from '@openmrs/esm-framework';
import { mockColumns, mockEncounter, mockEncounterType, mockForms } from '../../../../../__mocks__/encounter-list.mock';
import { launchPatientWorkspace } from '@openmrs/esm-patient-common-lib';
import * as encounterRowsHook from '../../hooks/useEncounterRows';
import * as formsJsonHook from '../../hooks/useFormsJson';

const emptyTestProps = {
formConceptMap: {},
patientUuid: 'some-uuid',
encounterType: mockEncounterType,
columns: [],
headerTitle: 'Sample header title encounter list',
description: 'Sample description encounter list',
formList: [],
filter: jest.fn(),
launchOptions: {
moduleName: '',
hideFormLauncher: false,
displayText: '',
},
};

const testProps = {
formConceptMap: {},
patientUuid: 'some-uuid',
encounterType: mockEncounterType,
columns: mockColumns,
headerTitle: 'Sample header title encounter list',
description: 'Sample description encounter list',
formList: mockForms,
filter: jest.fn(),
launchOptions: {
moduleName: '',
hideFormLauncher: false,
displayText: '',
},
};

jest.mock('../../hooks/useEncounterRows');
jest.mock('../../hooks/useFormsJson');

jest.mock('@openmrs/esm-patient-common-lib', () => ({
launchPatientWorkspace: jest.fn(),
}));

jest.mock('@openmrs/openmrs-form-engine-lib', () => ({
OHRIForm: jest
.fn()
.mockImplementation(() => React.createElement('div', { 'data-testid': 'openmrs form' }, 'FORM ENGINE LIB')),
}));

describe('EncounterList', () => {
afterEach(() => {
jest.clearAllMocks();
});

test('renders an loading state if data is loading', () => {
jest
.spyOn(encounterRowsHook, 'useEncounterRows')
.mockReturnValue({ encounters: [], isLoading: true, error: null, onFormSave: () => {} });

jest.spyOn(formsJsonHook, 'useFormsJson').mockReturnValue({ formsJson: [], isLoading: true });

act(() => {
render(<EncounterList {...emptyTestProps} />);
});
const element = document.querySelector('.cds--skeleton.cds--data-table-container');
expect(element).not.toBeNull();
});

test('renders an empty state if data is null', () => {
jest
.spyOn(encounterRowsHook, 'useEncounterRows')
.mockReturnValue({ encounters: [], isLoading: false, error: null, onFormSave: () => {} });

jest.spyOn(formsJsonHook, 'useFormsJson').mockReturnValue({ formsJson: [], isLoading: false });

act(() => {
render(<EncounterList {...emptyTestProps} />);
});
expect(
screen.getByText('There are no sample description encounter list to display for this patient'),
).toBeInTheDocument();
});

test('should render the encounter list component', () => {
jest.spyOn(encounterRowsHook, 'useEncounterRows').mockReturnValue({
encounters: mockEncounter,
isLoading: false,
error: null,
onFormSave: () => {},
});
jest.spyOn(formsJsonHook, 'useFormsJson').mockReturnValue({ formsJson: [], isLoading: false });

act(() => {
render(<EncounterList {...testProps} />);
});
expect(screen.getByText('Sample header title encounter list')).toBeInTheDocument();
expect(screen.getByText('Death Date')).toBeInTheDocument();
expect(screen.getByText('Click to sort rows by Cause of Death header in ascending order')).toBeInTheDocument();
expect(screen.getByText('Cause of Death')).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export const EncounterValuesTile: React.FC<EncounterValuesTileProps> = ({ patien
<span className={styles.tileValue}>--</span>
</div>
</div>
)
);
}

return (
Expand Down
5 changes: 1 addition & 4 deletions packages/esm-commons-lib/src/hooks/useEncounterRows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ import { encounterRepresentation } from '../constants';

export function useEncounterRows(patientUuid: string, encounterType: string, encounterFilter: (encounter) => boolean) {
const [encounters, setEncounters] = useState([]);
const url = useMemo(
() => `/ws/rest/v1/encounter?encounterType=${encounterType}&patient=${patientUuid}&v=${encounterRepresentation}`,
[encounterType, patientUuid],
);
const url = `/ws/rest/v1/encounter?encounterType=${encounterType}&patient=${patientUuid}&v=${encounterRepresentation}`;

const {
data: response,
Expand Down
2 changes: 1 addition & 1 deletion packages/esm-commons-lib/src/hooks/useFormsJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function useFormsJson(formNames: string[]) {
setOpenmrsForms(
responses
.map((response, index) => {
const match = response.data.results.find((result) => !result.retired && result.name === formNames[index]);
const match = response?.data?.results.find((result) => !result.retired && result.name === formNames[index]);
if (!match) {
console.error('Form not found: ' + formNames[index]);
return null;
Expand Down
2 changes: 1 addition & 1 deletion packages/esm-commons-lib/src/hooks/useLastEncounter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import useSWR from 'swr';

export function useLastEncounter(patientUuid: string, encounterType: string) {
const query = `encounterType=${encounterType}&patient=${patientUuid}&limit=1&order=desc&startIndex=0`;
const endpointUrl = `/ws/rest/v1/encounter?${query}&v=${encounterRepresentation}`;
const endpointUrl = `/ws/rest/v1/encounter?${query}&v=${encounterRepresentation}`;

const { data, error, isValidating } = useSWR<{ data: { results: Array<OpenmrsEncounter> } }, Error>(
endpointUrl,
Expand Down
18 changes: 6 additions & 12 deletions packages/esm-commons-lib/src/hooks/usePatientDeathStatus.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
import { openmrsFetch } from '@openmrs/esm-framework';
import { useEffect, useState } from 'react';
import useSWRImmutable from 'swr';

export function usePatientDeathStatus(patientUuid: string) {
const [isDead, setIsDead] = useState(false);
const { data: response } = useSWRImmutable<any, Error>(
`/ws/rest/v1/person/${patientUuid}?v=custom:(dead)`,
openmrsFetch,
);
const {
data: response,
isLoading,
error,
} = useSWRImmutable<any, Error>(`/ws/rest/v1/person/${patientUuid}?v=custom:(dead)`, openmrsFetch);

useEffect(() => {
if (response) {
setIsDead(response.data.dead);
}
}, [response]);
return {
isDead,
isDead: !isLoading && !error && response ? response?.data?.dead : false,
};
}
4 changes: 2 additions & 2 deletions packages/esm-covid-app/src/dashboard.meta.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ export const covid19CasesDashboardMeta = {
title: 'COVID-19 Cases',
isFolder: true,
folderTitle: 'COVID',
folderIcon: Coronavirus
};
folderIcon: Coronavirus,
};
2 changes: 1 addition & 1 deletion packages/esm-covid-app/src/root.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ const Root: React.FC = () => {
);
};

export default Root;
export default Root;
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ function FormRenderTest() {
};

const formValidation = () => {
handleFormValidation(schemaInput, dataTypeToRenderingMap).then((response) => console.log(response));
handleFormValidation(schemaInput, dataTypeToRenderingMap);
};

const handleFormSubmission = (e) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/esm-hiv-app/src/dashboard.meta.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export const hivCareAndTreatmentFolderDashboardMeta = {
title: 'HIV Care and Treatment',
name: 'care-and-treatment',
folderTitle: 'Care and Treatment',
folderIcon : Home
folderIcon: Home,
};

export const hivPreventionFolderDashboardMeta = {
Expand All @@ -93,7 +93,7 @@ export const hivPreventionFolderDashboardMeta = {
title: 'HIV Testing Services',
name: 'hts',
folderTitle: 'HIV Prevention',
folderIcon : Pills
folderIcon: Pills,
};

export const htsDashboardMeta = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,8 @@ const CD4ResultsList: React.FC<CD4ResultsListProps> = ({ patientUuid }) => {
for (let patient of patients) {
const lastCd4Result = patientToCd4Map.find((entry) => entry.patientId === patient.resource.id)?.cd4Result;
const lastCd4ResultDate = patientToCd4Map.find((entry) => entry.patientId === patient.resource.id)?.cd4ResultDate;
const lastCd4EncounterUuid = patientToCd4Map.find(
(entry) => entry.patientId === patient.resource.id,
)?.cd4EncounterUuid;
const lastCd4EncounterUuid = patientToCd4Map.find((entry) => entry.patientId === patient.resource.id)
?.cd4EncounterUuid;
const patientActions = (
<LabresultsFormViewer
form={{ package: 'hiv', name: 'cd4_lab_results' }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,12 @@ const ViralLoadResultsList: React.FC<ViralLoadResultsListProps> = () => {
useEffect(() => {
let rows = [];
for (let patient of patients) {
const lastviralLoadResult = patientToViralLoadMap.find(
(entry) => entry.patientId === patient.resource.id,
)?.viralLoadResult;
const lastviralLoadResultDate = patientToViralLoadMap.find(
(entry) => entry.patientId === patient.resource.id,
)?.viralLoadResultDate;
const lastViralLoadEncounterUuid = patientToViralLoadMap.find(
(entry) => entry.patientId === patient.resource.id,
)?.viralEncounterUuid;
const lastviralLoadResult = patientToViralLoadMap.find((entry) => entry.patientId === patient.resource.id)
?.viralLoadResult;
const lastviralLoadResultDate = patientToViralLoadMap.find((entry) => entry.patientId === patient.resource.id)
?.viralLoadResultDate;
const lastViralLoadEncounterUuid = patientToViralLoadMap.find((entry) => entry.patientId === patient.resource.id)
?.viralEncounterUuid;
const patientActions = (
<LabresultsFormViewer
form={{ package: 'hiv', name: 'viral_load_results' }}
Expand Down
2 changes: 1 addition & 1 deletion packages/esm-ohri-core-app/src/dashboard.meta.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ export const patientListMeta = {
config: { columns: 1, type: 'grid', icon: ListBulleted },
isLink: true,
title: 'Patient Lists',
};
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';

const ProgramsHome = () => {
return <div style={{ margin: '1rem 1rem 0 1rem'}}>Programmes</div>;
return <div style={{ margin: '1rem 1rem 0 1rem' }}>Programmes</div>;
};

export default ProgramsHome;
2 changes: 1 addition & 1 deletion packages/esm-ohri-pmtct-app/src/dashboard.meta.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ export const motherChildDashboardMeta = {
name: 'mother-child-health',
slot: 'mother-child-health-dashboard-slot',
title: 'Maternal & Child Health',
icon: PedestrianChild
icon: PedestrianChild,
};
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function TbSummaryTiles() {
linkAddress: '#',
subTitle: t('drugResistant', 'Cases with drug resistant TB'),
value: activeDRClientsCount,
}
},
],
[activeDSClientsCount, activeDRClientsCount],
);
Expand Down

0 comments on commit 28ee703

Please sign in to comment.