Skip to content

Commit

Permalink
Merge pull request #90 from gosh-dre/feature/redirect-after-submit
Browse files Browse the repository at this point in the history
Feature/redirect after submit
  • Loading branch information
stefpiatek authored Nov 14, 2022
2 parents 300fae6 + 778e941 commit 92d6cb1
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 26 deletions.
52 changes: 34 additions & 18 deletions src/components/reports/ReportForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { createPractitioner, deleteFhirData, TestReportForm } from "../../fhir/t
import { Practitioner } from "@smile-cdr/fhirts/dist/FHIR-R4/classes/practitioner";
import { createIdentifier } from "../../fhir/resource_helpers";
import { GOSH_GENETICS_IDENTIFIER } from "../../fhir/resources";
import { BrowserRouter } from "react-router-dom";
import { mockedNavigate } from "../../setupTests";

const clearAndType = (element: Element, value: string) => {
userEvent.clear(element);
Expand Down Expand Up @@ -157,14 +159,17 @@ describe("Report form", () => {
// Arrange
const practitioner = new Practitioner();
practitioner.resourceType = "Practitioner";
const identifier = createIdentifier(`always_the_same_report_${GOSH_GENETICS_IDENTIFIER}`);
practitioner.identifier = [identifier];
// Adding in duplicate identifier for tests, but also for running in front end with form defaults
practitioner.identifier = [
createIdentifier(`always_the_same_report_${GOSH_GENETICS_IDENTIFIER}`),
createIdentifier(`anapietra_report_${GOSH_GENETICS_IDENTIFIER}`),
];

await createPractitioner(practitioner);
await createPractitioner(practitioner);

// Act
render(<TestReportForm />);
// Act - breakpoint here to submit in browser and see the modal
render(<TestReportForm />, { wrapper: BrowserRouter });
await setLabAndPatient();
await setSample();
await setVariantFields();
Expand All @@ -175,19 +180,22 @@ describe("Report form", () => {
});

// Assert
await waitFor(() => {
expect(screen.getByText(/error/i, { selector: "h2" })).toBeInTheDocument();
});
await waitFor(
() => {
expect(screen.getByText(/error/i, { selector: "h2" })).toBeInTheDocument();
expect(mockedNavigate).not.toBeCalled();
},
{ timeout: 2000 },
);
});
/**
* Given the report form
* When all data filled in
* Then the rendered result should be rendered in an alert box
* Then the user should be redirected and no errors should be found
*/
test("Report with variant", async () => {
// Arrange
render(<TestReportForm />);

render(<TestReportForm />, { wrapper: BrowserRouter });
// Act
await setLabAndPatient();
await setSample();
Expand All @@ -196,21 +204,24 @@ describe("Report form", () => {
await act(async () => {
userEvent.click(screen.getByText(/submit/i));
});

// Assert
const result = await screen.findByRole("alert");
expect(result).toBeInTheDocument();
await waitFor(
() => {
expect(screen.queryByText(/error/i, { selector: "h2" })).not.toBeInTheDocument();
expect(mockedNavigate).toBeCalled();
},
{ timeout: 15000 },
);
});

/**
* Given the report form
* When all data filled in except for having no variant
* Then the rendered result should be rendered in an alert box
* Then the user should be redirected and no errors should be found
*/
test("Report without variant", async () => {
// Arrange
render(<TestReportForm />);

render(<TestReportForm />, { wrapper: BrowserRouter });
// Act
await setLabAndPatient();
await setSample();
Expand All @@ -221,7 +232,12 @@ describe("Report form", () => {
});

// Assert
const result = await screen.findByRole("alert");
expect(result).toBeInTheDocument();
await waitFor(
() => {
expect(screen.queryByText(/error/i, { selector: "h2" })).not.toBeInTheDocument();
expect(mockedNavigate).toBeCalled();
},
{ timeout: 10000 },
);
});
});
14 changes: 6 additions & 8 deletions src/components/reports/ReportForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import Report from "./formSteps/Report";
import Confirmation from "./formSteps/Confirmation";
import FormStepBtn from "../UI/FormStepBtn";
import { RequiredCoding } from "../../code_systems/types";
import { useNavigate } from "react-router-dom";
import ModalWrapper, { ModalState } from "../UI/ModalWrapper";
import { FhirRequest } from "../../fhir/types";

Expand Down Expand Up @@ -52,12 +53,12 @@ type SetFieldValue = (field: string, value: any, shouldValidate?: boolean) => vo

const ReportForm: FC<Props> = (props: Props) => {
const [modal, setModal] = useState<ModalState | null>(null);
const [result, setResult] = useState("");
const [formStep, setFormStep] = useState(0);
const [reportedGenes, setReportedGenes] = useState<RequiredCoding[]>([]);
const isLastStep = formStep === steps.length - 1;
const ctx = useContext(FhirContext);
const formRef = useRef<FormikProps<FormValues>>(null);
const navigate = useNavigate();

const submitForm = (values: FormValues, actions: FormikHelpers<FormValues>) => {
let bundle: FhirRequest = { body: "No data set", headers: {}, method: "POST", url: "/" };
Expand All @@ -75,16 +76,16 @@ const ReportForm: FC<Props> = (props: Props) => {
return;
}
const bodyJson = JSON.parse(bundle.body as string);

const result = JSON.stringify(bodyJson, null, 2);
setResult(result);
const resourceList = bodyJson.entry.map((entry: any) => entry.resource.resourceType);

ctx.client
?.request(bundle)
.then((response) => {
console.debug(bundle, response);
const errors = getErrors(response, resourceList);
if (errors.length > 0) {
if (errors.length === 0) {
navigate("/", { replace: true });
} else {
const errorsTable = (
<>
<table className={classes["errors-table"]}>
Expand Down Expand Up @@ -117,15 +118,13 @@ const ReportForm: FC<Props> = (props: Props) => {
isError: true,
});
});

actions.setSubmitting(false);
};
const handleSubmit = (values: FormValues, actions: FormikHelpers<FormValues>) => {
if (formStep === steps.length - 1) {
submitForm(values, actions);
return;
}

// validate form fields
actions.setTouched({});
actions.setSubmitting(false);
Expand Down Expand Up @@ -186,7 +185,6 @@ const ReportForm: FC<Props> = (props: Props) => {
</Form>
)}
</Formik>
{result !== "" && <textarea id="resultOutput" role="alert" rows={80} cols={100} defaultValue={result} />}
</Card>
</>
);
Expand Down
10 changes: 10 additions & 0 deletions src/setupTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ import { enableFetchMocks } from "jest-fetch-mock";
import { createIdentifier } from "./fhir/resource_helpers";
import { createPractitioner } from "./fhir/testUtilities";

jest.resetAllMocks();
/**
* Mocking the return value of useNavigate so that we can determine if a component will redirect the user.
*/
export const mockedNavigate = jest.fn();
jest.mock("react-router-dom", () => ({
...(jest.requireActual("react-router-dom") as any),
useNavigate: () => mockedNavigate,
}));

beforeAll(async () => {
/*
* For some reason on first load of FHIR server, creating a batch of requests doesn't seem to validate
Expand Down

0 comments on commit 92d6cb1

Please sign in to comment.