Skip to content

Commit

Permalink
(test) Fix failing tests by removing partial framework mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
denniskigen committed Aug 1, 2024
1 parent 889b4d2 commit 100d690
Show file tree
Hide file tree
Showing 10 changed files with 328 additions and 265 deletions.
10 changes: 10 additions & 0 deletions __mocks__/session.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export const mockSessionDataResponse = {
address13: null,
address14: null,
address15: null,
links: [],
},
user: {
uuid: '45ce6c2e-dd5a-11e6-9d9c-0242ac150002',
Expand All @@ -77,31 +78,40 @@ export const mockSessionDataResponse = {
{
uuid: '62431c71-5244-11ea-a771-0242ac160002',
display: 'Manage Appointment Services',
links: [],
},
{
uuid: '6206682c-5244-11ea-a771-0242ac160002',
display: 'Manage Appointments',
links: [],
},
{
uuid: '6280ff58-5244-11ea-a771-0242ac160002',
display: 'Manage Appointment Specialities',
links: [],
},
],
roles: [
{
uuid: '8d94f852-c2cc-11de-8d13-0010c6dffd0f',
display: 'System Developer',
links: [],
},
{
uuid: '62c195c5-5244-11ea-a771-0242ac160002',
display: 'Bahmni Role',
links: [],
},
{
uuid: '8d94f280-c2cc-11de-8d13-0010c6dffd0f',
display: 'Provider',
links: [],
},
],
retired: false,
locale: 'en_GB',
allowedLocales: ['en_GB'],
},
sessionId: 'D4F7D4D4-6A6D-4D4D-8D4D-4D4D4D4D4D4D',
},
};
28 changes: 13 additions & 15 deletions src/components/inputs/date/date.component.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
import React, { useEffect, useMemo, useState } from 'react';
import React, { useContext, useEffect, useMemo, useState } from 'react';
import classNames from 'classnames';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';
import { useField } from 'formik';
import { useTranslation } from 'react-i18next';
import { Layer, TimePicker } from '@carbon/react';
import classNames from 'classnames';
import { OpenmrsDatePicker, formatDate, formatTime } from '@openmrs/esm-framework';
import { type FormFieldProps } from '../../../types';
import { isTrue } from '../../../utils/boolean-utils';
import { isInlineView } from '../../../utils/form-helper';
import { isEmpty } from '../../../validators/form-validator';
import { FormContext } from '../../../form-context';
import FieldValueView from '../../value/view/field-value-view.component';
import RequiredFieldLabel from '../../required-field-label/required-field-label.component';
import styles from './date.scss';
import { useFieldValidationResults } from '../../../hooks/useFieldValidationResults';
import { OpenmrsDatePicker, formatDate, formatTime } from '@openmrs/esm-framework';
import { type CalendarDate, getLocalTimeZone } from '@internationalized/date';
import styles from './date.scss';

const DateField: React.FC<FormFieldProps> = ({ question, onChange, handler, previousValue }) => {
const { t } = useTranslation();
const [field] = useField(question.id);
const { setFieldValue, encounterContext, layoutType, workspaceLayout, fields } = React.useContext(FormContext);
const { setFieldValue, encounterContext, layoutType, workspaceLayout, fields } = useContext(FormContext);
const [time, setTime] = useState('');
const { errors, setErrors, warnings, setWarnings } = useFieldValidationResults(question);

Expand All @@ -30,12 +29,11 @@ const DateField: React.FC<FormFieldProps> = ({ question, onChange, handler, prev
return false;
}, [encounterContext.sessionMode, question.readonly, question.inlineRendering, layoutType, workspaceLayout]);

const onDateChange = (date: CalendarDate) => {
const refinedDate = date.toDate(getLocalTimeZone());
setTimeIfPresent(refinedDate, time);
setFieldValue(question.id, refinedDate);
onChange(question.id, refinedDate, setErrors, setWarnings);
handler?.handleFieldSubmission(question, refinedDate, encounterContext);
const onDateChange = (date: Date) => {
setTimeIfPresent(date, time);
setFieldValue(question.id, date);
onChange(question.id, date, setErrors, setWarnings);
handler?.handleFieldSubmission(question, date, encounterContext);
};

const setTimeIfPresent = (date: Date, time: string) => {
Expand Down Expand Up @@ -64,7 +62,7 @@ const DateField: React.FC<FormFieldProps> = ({ question, onChange, handler, prev
} else {
const time = event.target.value;
setTime(time);
const dateValue = question.datePickerFormat === 'timer' ? new Date() : field.value;
const dateValue = question.datePickerFormat === 'timer' ? new Date() : new Date(field.value);
setTimeIfPresent(dateValue, time);
setFieldValue(question.id, dateValue);
onChange(question.id, dateValue, setErrors, setWarnings);
Expand Down Expand Up @@ -127,7 +125,7 @@ const DateField: React.FC<FormFieldProps> = ({ question, onChange, handler, prev
className={classNames(styles.boldedLabel, styles.timeInput)}
id={question.id}
labelText={
question.isRequired ? (
question.required ? (
<RequiredFieldLabel
label={question.datePickerFormat === 'timer' ? t(question.label) : t('time', 'Time')}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,21 @@
import React from 'react';
import { act, render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import { type FetchResponse, openmrsFetch, usePatient, useSession } from '@openmrs/esm-framework';
import { type FormSchema } from '../../../types';
import { mockPatient } from '__mocks__/patient.mock';
import { mockSessionDataResponse } from '__mocks__/session.mock';
import { mockVisit } from '__mocks__/visit.mock';
import multiSelectFormSchema from '__mocks__/forms/rfe-forms/multi-select-form.json';
import FormEngine from '../../../form-engine.component';

const mockOpenmrsFetch = jest.fn();
global.ResizeObserver = require('resize-observer-polyfill');
const visit = mockVisit;
const patientUUID = '8673ee4f-e2ab-4077-ba55-4980f408773e';

jest.mock('@openmrs/esm-framework', () => {
const originalModule = jest.requireActual('@openmrs/esm-framework');
const mockOpenmrsFetch = jest.mocked(openmrsFetch);
const mockUseSession = jest.mocked(useSession);
const mockUsePatient = jest.mocked(usePatient);

return {
...originalModule,
createErrorHandler: jest.fn(),
showNotification: jest.fn(),
showToast: jest.fn(),
getAsyncLifecycle: jest.fn(),
usePatient: jest.fn().mockImplementation(() => ({ patient: mockPatient })),
registerExtension: jest.fn(),
useSession: jest.fn().mockImplementation(() => mockSessionDataResponse.data),
openmrsFetch: jest.fn().mockImplementation((args) => mockOpenmrsFetch(args)),
};
});
const visit = mockVisit;
const patientUUID = '8673ee4f-e2ab-4077-ba55-4980f408773e';

jest.mock('../../../api/api', () => {
const originalModule = jest.requireActual('../../../api/api');
Expand Down Expand Up @@ -56,7 +44,22 @@ const renderForm = async () => {
);
};

describe('OHRIMultiSelect Component', () => {
describe('MultiSelect Component', () => {
beforeEach(() => {
mockOpenmrsFetch.mockResolvedValue({
data: { results: [{ ...multiSelectFormSchema }] },
} as unknown as FetchResponse);

mockUseSession.mockReturnValue(mockSessionDataResponse.data);

mockUsePatient.mockReturnValue({
isLoading: false,
patient: mockPatient,
patientUuid: mockPatient.id,
error: null,
});
});

it('renders correctly', async () => {
await renderForm();
expect(screen.getByRole('combobox', { name: /Patient covered by NHIF/i })).toBeInTheDocument();
Expand Down
33 changes: 15 additions & 18 deletions src/components/inputs/unspecified/unspecified.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,27 @@ import React from 'react';
import dayjs from 'dayjs';
import { parseDate } from '@internationalized/date';
import { fireEvent, render, screen } from '@testing-library/react';
import { OpenmrsDatePicker } from '@openmrs/esm-framework';
import { Formik } from 'formik';
import { type FormField, type EncounterContext, FormContext } from '../../..';
import { findTextOrDateInput } from '../../../utils/test-utils';
import { ObsSubmissionHandler } from '../../../submission-handlers/obsHandler';
import DateField from '../date/date.component';
import UnspecifiedField from './unspecified.component';
import { ObsSubmissionHandler } from '../../../submission-handlers/obsHandler';

jest.mock('@openmrs/esm-framework', () => {
const originalModule = jest.requireActual('@openmrs/esm-framework');
return {
...originalModule,
OpenmrsDatePicker: jest.fn().mockImplementation(({ id, labelText, value, onChange }) => {
return (
<>
<label htmlFor={id}>{labelText}</label>
<input
id={id}
value={value ? dayjs(value).format('DD/MM/YYYY') : undefined}
onChange={(evt) => onChange(parseDate(dayjs(evt.target.value).format('YYYY-MM-DD')))}
/>
</>
);
}),
};
const mockOpenmrsDatePicker = jest.mocked(OpenmrsDatePicker);

mockOpenmrsDatePicker.mockImplementation(({ id, labelText, value, onChange }) => {
return (
<>
<label htmlFor={id}>{labelText}</label>
<input
id={id}
value={value ? dayjs(value).format('DD/MM/YYYY') : undefined}

Check failure on line 21 in src/components/inputs/unspecified/unspecified.test.tsx

View workflow job for this annotation

GitHub Actions / build

No overload matches this call.
onChange={(evt) => onChange(parseDate(dayjs(evt.target.value).format('YYYY-MM-DD')))}

Check failure on line 22 in src/components/inputs/unspecified/unspecified.test.tsx

View workflow job for this annotation

GitHub Actions / build

Argument of type 'CalendarDate' is not assignable to parameter of type 'Date'.
/>
</>
);
});

const question: FormField = {
Expand Down
2 changes: 1 addition & 1 deletion src/components/section/form-section.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ function ErrorFallback({ error }) {
const { t } = useTranslation();
return (
<ToastNotification
ariaLabel={t('closesNotification', 'Closes notification')}
aria-label={t('closesNotification', 'Closes notification')}
caption=""
hideCloseButton
lowContrast
Expand Down
66 changes: 34 additions & 32 deletions src/form-engine.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react';
import dayjs from 'dayjs';
import userEvent from '@testing-library/user-event';
import { act, cleanup, render, screen, within, fireEvent, waitFor } from '@testing-library/react';
import { restBaseUrl } from '@openmrs/esm-framework';
import { OpenmrsDatePicker, openmrsFetch, restBaseUrl, usePatient, useSession } from '@openmrs/esm-framework';
import { parseDate } from '@internationalized/date';
import { when } from 'jest-when';
import * as api from '../src/api/api';
Expand Down Expand Up @@ -37,47 +37,24 @@ import conditionalRequiredTestForm from '__mocks__/forms/rfe-forms/conditional-r
import conditionalAnsweredForm from '__mocks__/forms/rfe-forms/conditional-answered-form.json';
import FormEngine from './form-engine.component';

global.ResizeObserver = require('resize-observer-polyfill');

const patientUUID = '8673ee4f-e2ab-4077-ba55-4980f408773e';
const visit = mockVisit;
const mockOpenmrsFetch = jest.fn();

const formsResourcePath = when((url: string) => url.includes(`${restBaseUrl}/form/`));
const clobdataResourcePath = when((url: string) => url.includes(`${restBaseUrl}/clobdata/`));
global.ResizeObserver = require('resize-observer-polyfill');

const mockOpenmrsDatePicker = jest.mocked(OpenmrsDatePicker);
const mockOpenmrsFetch = jest.mocked(openmrsFetch);
const mockUsePatient = jest.mocked(usePatient);
const mockUseSession = jest.mocked(useSession);

when(mockOpenmrsFetch).calledWith(formsResourcePath).mockReturnValue({ data: demoHtsOpenmrsForm });
when(mockOpenmrsFetch).calledWith(clobdataResourcePath).mockReturnValue({ data: demoHtsForm });

const locale = window.i18next.language == 'en' ? 'en-GB' : window.i18next.language;

jest.mock('@openmrs/esm-framework', () => {
const originalModule = jest.requireActual('@openmrs/esm-framework');

return {
...originalModule,
createErrorHandler: jest.fn(),
showNotification: jest.fn(),
showToast: jest.fn(),
getAsyncLifecycle: jest.fn(),
usePatient: jest.fn().mockImplementation(() => ({ patient: mockPatient })),
registerExtension: jest.fn(),
useSession: jest.fn().mockImplementation(() => mockSessionDataResponse.data),
openmrsFetch: jest.fn().mockImplementation((args) => mockOpenmrsFetch(args)),
OpenmrsDatePicker: jest.fn().mockImplementation(({ id, labelText, value, onChange, isInvalid, invalidText }) => {
return (
<>
<label htmlFor={id}>{labelText}</label>
<input
id={id}
value={value ? dayjs(value).format('DD/MM/YYYY') : undefined}
onChange={(evt) => onChange(parseDate(dayjs(evt.target.value).format('YYYY-MM-DD')))}
/>
{isInvalid && invalidText && <span>{invalidText}</span>}
</>
);
}),
};
});

jest.mock('../src/api/api', () => {
const originalModule = jest.requireActual('../src/api/api');

Expand All @@ -93,6 +70,31 @@ jest.mock('../src/api/api', () => {

jest.mock('./hooks/useRestMaxResultsCount', () => jest.fn().mockReturnValue({ systemSetting: { value: '50' } }));

mockUseSession.mockReturnValue(mockSessionDataResponse.data);

mockUsePatient.mockReturnValue({
error: null,
isLoading: false,
patient: mockPatient,
patientUuid: mockPatient.id,
});

mockOpenmrsDatePicker.mockImplementation(
({ id, onChange, labelText, invalidText, isDisabled, isReadOnly, isRequired, isInvalid, value }) => {
return (
<>
<label htmlFor={id}>{labelText}</label>
<input
id={id}
value={value ? dayjs(value).format('DD/MM/YYYY') : undefined}

Check failure on line 89 in src/form-engine.test.tsx

View workflow job for this annotation

GitHub Actions / build

No overload matches this call.
onChange={(evt) => onChange(parseDate(dayjs(evt.target.value).format('YYYY-MM-DD')))}

Check failure on line 90 in src/form-engine.test.tsx

View workflow job for this annotation

GitHub Actions / build

Argument of type 'CalendarDate' is not assignable to parameter of type 'Date'.
/>
{isInvalid && invalidText && <span>{invalidText}</span>}
</>
);
},
);

describe('Form engine component', () => {
const user = userEvent.setup();

Expand Down
Loading

0 comments on commit 100d690

Please sign in to comment.