Skip to content

Commit

Permalink
Update tests (#1427)
Browse files Browse the repository at this point in the history
* Update and fix failing tests

* Fix Linting error
  • Loading branch information
ciremusyoka authored Jun 5, 2024
1 parent b8e0314 commit f1ddbbe
Show file tree
Hide file tree
Showing 7 changed files with 416 additions and 226 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ describe('components/forms/CreateTeamForm', () => {
});

wrapper.update();
await act(async () => {
await flushPromises();
});
// name is required and has no default
expect(wrapper.find('#name .ant-form-item').text()).toMatchInlineSnapshot(
`"NameName is Required"`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export const columns = (t: TFunction, showPatientOverview: ShowPatientOverview)
render: (record: PatientTableData) => (
<span className="d-flex justify-content-start align-items-center">
<Button
data-testid={record.id}
onClick={() => showPatientOverview(record.id as string)}
type="link"
className="m-0 p-1"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const PatientDetailsOverview = (props: PatientListViewProps) => {
UUID: identifier && identifier.length > 0 ? identifier[0]?.value : '',
Phone: telecom && telecom.length > 0 ? telecom[0].value : '',
Address: address?.[0]?.line?.[0] ?? '',
'Date of Birth': birthDate,
'Date of birth': birthDate,
MRN: 'Unknown',
Country: address && address.length > 0 ? address[0]?.country : '',
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {
cleanup,
render,
screen,
fireEvent,
waitForElementToBeRemoved,
} from '@testing-library/react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { MemoryRouter } from 'react-router-dom';
import { Route, Router, Switch } from 'react-router-dom';
import { PatientDetailsOverview } from '..';
import nock from 'nock';
import { store } from '@opensrp/store';
import { createMemoryHistory } from 'history';
import { authenticateUser } from '@onaio/session-reducer';
import { Provider } from 'react-redux';
import { LIST_PATIENTS_URL } from '../../../constants';
import { patientResourceDetails } from '../../PatientDetails/tests/fixtures';

const queryClient = new QueryClient({
defaultOptions: {
Expand All @@ -15,105 +26,133 @@ const queryClient = new QueryClient({
},
});

describe('PatientDetailsOverview', () => {
beforeEach(() => {
queryClient.clear();
nock.cleanAll();
});
jest.mock('fhirclient', () => {
return jest.requireActual('fhirclient/lib/entry/browser');
});

beforeAll(() => {
nock.disableNetConnect();
store.dispatch(
authenticateUser(
true,
{
email: 'bob@example.com',
name: 'Bobbie',
username: 'RobertBaratheon',
},
{ api_token: 'hunter2', oAuth2Data: { access_token: 'sometoken', state: 'abcde' } }
)
);
});

afterAll(() => {
nock.enableNetConnect();
});

afterEach(() => {
nock.cleanAll();
cleanup();
});

const renderComponent = (patientId) => {
const searchParams = new URLSearchParams();
if (patientId) {
searchParams.set('viewDetails', patientId);
}
const { id: patientId } = patientResourceDetails;
const props = {
fhirBaseURL: 'http://test.server.org',
};

return render(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const AppWrapper = (props: any) => {
return (
<Provider store={store}>
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<PatientDetailsOverview fhirBaseURL="https://example.com/fhir" />
</MemoryRouter>
</QueryClientProvider>,
{
wrapper: ({ children }) => (
<div data-query-params={searchParams.toString()}>{children}</div>
),
}
);
};

it('renders loading state when fetching patient data', async () => {
renderComponent('123');
expect(screen.getByText(/Fetching Patient details/i)).toBeInTheDocument();
});

it('renders error state when an error occurs', async () => {
nock('https://example.com').get('/fhir/Patient/123').replyWithError('Error fetching data');

renderComponent('123');

await waitFor(() => {
expect(screen.getByText(/Error fetching data/i)).toBeInTheDocument();
});
});

it('renders patient details when data is fetched successfully', async () => {
const mockPatientData = {
id: '1',
gender: 'Male',
birthDate: '1990-01-01',
address: [{ line: ['123 Street'], country: 'Country' }],
telecom: [{ value: '1234567890' }],
identifier: [{ value: '123456' }],
deceasedBoolean: false,
active: true,
};

nock('https://example.com').get('/fhir/Patient/1').reply(200, mockPatientData);

renderComponent('1');

await waitFor(() => {
expect(screen.getByText(/123456/i)).toBeInTheDocument(); // patient ID
expect(screen.getByText(/Male/i)).toBeInTheDocument(); // gender
expect(screen.getByText(/1234567890/i)).toBeInTheDocument(); // phone number
expect(screen.getByText(/123 Street/i)).toBeInTheDocument(); // address
expect(screen.getByText(/1990-01-01/i)).toBeInTheDocument(); // date of birth
expect(screen.getByText(/View full details/i)).toBeInTheDocument(); // link to full details
});
});

it('renders "BrokenPage" when patient is not found', async () => {
nock('https://example.com').get('/fhir/Patient/999').reply(404);

renderComponent('999');

await waitFor(() => {
expect(screen.getByText(/patient not found/i)).toBeInTheDocument();
expect(
screen.getByText(/The patient you are looking for does not exist/i)
).toBeInTheDocument();
});
});

it('clicking close button calls removeParam function', async () => {
const mockPatientData = {
id: '1',
gender: 'Male',
birthDate: '1990-01-01',
address: [{ line: ['123 Street'], country: 'Country' }],
telecom: [{ value: '1234567890' }],
identifier: [{ value: '123456' }],
deceasedBoolean: false,
active: true,
};

nock('https://example.com').get('/fhir/Patient/1').reply(200, mockPatientData);

renderComponent('1');

await waitFor(() => screen.getByText(/View full details/i));

userEvent.click(screen.getByTestId('cancel'));
expect(window.location.search).not.toContain('viewDetails');
});
<Switch>
<Route exact path={`${LIST_PATIENTS_URL}`}>
{(routeProps) => <PatientDetailsOverview {...{ ...props, ...routeProps }} />}
</Route>
</Switch>
</QueryClientProvider>
</Provider>
);
};

it('renders error state when an error occurs', async () => {
const history = createMemoryHistory();
history.push(`${LIST_PATIENTS_URL}?viewDetails=${patientId}`);
nock(props.fhirBaseURL).get(`/Patient/${patientId}`).replyWithError('Error fetching data');

render(
<Router history={history}>
<AppWrapper {...props}></AppWrapper>
</Router>
);

await waitForElementToBeRemoved(document.querySelector('.ant-alert-content'));
expect(screen.getByText(/error fetching data/i)).toBeInTheDocument();
});

it('renders patient details when data is fetched successfully', async () => {
const history = createMemoryHistory();
history.push(`${LIST_PATIENTS_URL}?viewDetails=${patientId}`);
nock(props.fhirBaseURL).get(`/Patient/${patientId}`).reply(200, patientResourceDetails);

render(
<Router history={history}>
<AppWrapper {...props}></AppWrapper>
</Router>
);

await waitForElementToBeRemoved(document.querySelector('.ant-alert-content'));
const bodyElementValues = [...document.querySelectorAll('.singleKeyValue-pair__default')].map(
(keyValue) => keyValue.textContent
);
expect(bodyElementValues).toEqual([
'UUID',
'Phone+254722123456',
'Address213,One Pademore',
'Date of birth1988-08-04',
'MRNUnknown',
'CountryKenya',
]);

const headerLeftElementValues = document.querySelector('.header-bottom');
expect(headerLeftElementValues?.textContent).toEqual('ID: 1Gender: male');
expect(history.location.search).toEqual(`?viewDetails=${patientId}`);

const closeBtn = screen.findByTestId('cancel');
fireEvent.click(await closeBtn);
expect(history.location.pathname).toEqual(LIST_PATIENTS_URL);
expect(history.location.search).toEqual('');
});

it('Navigate to details page', async () => {
const history = createMemoryHistory();
history.push(`${LIST_PATIENTS_URL}?viewDetails=${patientId}`);
nock(props.fhirBaseURL).get(`/Patient/${patientId}`).reply(200, patientResourceDetails);

render(
<Router history={history}>
<AppWrapper {...props}></AppWrapper>
</Router>
);

await waitForElementToBeRemoved(document.querySelector('.ant-alert-content'));
const FullDetailsLink = screen.findByRole('link', { name: 'View full details' });
fireEvent.click(await FullDetailsLink);
expect(history.location.pathname).toEqual(`${LIST_PATIENTS_URL}/${patientId}`);
});

it('renders null when patient Id not found', async () => {
const history = createMemoryHistory();
history.push(LIST_PATIENTS_URL);

render(
<Router history={history}>
<AppWrapper {...props}></AppWrapper>
</Router>
);

expect(document.querySelector('body')).toMatchInlineSnapshot(`
<body>
<div />
</body>
`);
});
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,15 @@ exports[`renders correctly in list view: table row 1 page 1 5`] = `
<span
class="d-flex justify-content-start align-items-center"
>
<a
class="m-0 p-1"
href="/fhir/Patient/52"
<button
class="ant-btn css-dev-only-do-not-override-k7429z ant-btn-link m-0 p-1"
data-testid="52"
type="button"
>
View
</a>
<span>
View
</span>
</button>
</span>
</td>
`;
Expand Down Expand Up @@ -123,12 +126,15 @@ exports[`renders correctly in list view: table row 2 page 1 5`] = `
<span
class="d-flex justify-content-start align-items-center"
>
<a
class="m-0 p-1"
href="/fhir/Patient/2"
<button
class="ant-btn css-dev-only-do-not-override-k7429z ant-btn-link m-0 p-1"
data-testid="2"
type="button"
>
View
</a>
<span>
View
</span>
</button>
</span>
</td>
`;
Expand Down Expand Up @@ -179,12 +185,15 @@ exports[`renders correctly in list view: table row 3 page 1 5`] = `
<span
class="d-flex justify-content-start align-items-center"
>
<a
class="m-0 p-1"
href="/fhir/Patient/1"
<button
class="ant-btn css-dev-only-do-not-override-k7429z ant-btn-link m-0 p-1"
data-testid="1"
type="button"
>
View
</a>
<span>
View
</span>
</button>
</span>
</td>
`;
Expand Down Expand Up @@ -240,12 +249,15 @@ exports[`renders correctly in list view: table row 4 page 1 5`] = `
<span
class="d-flex justify-content-start align-items-center"
>
<a
class="m-0 p-1"
href="/fhir/Patient/3"
<button
class="ant-btn css-dev-only-do-not-override-k7429z ant-btn-link m-0 p-1"
data-testid="3"
type="button"
>
View
</a>
<span>
View
</span>
</button>
</span>
</td>
`;
Loading

0 comments on commit f1ddbbe

Please sign in to comment.