Skip to content

Instantly share code, notes, and snippets.

@adamjarling
Created September 27, 2020 19:21
Show Gist options
  • Save adamjarling/950fe3b5165ac45b914cbbb7373ed7d1 to your computer and use it in GitHub Desktop.
Save adamjarling/950fe3b5165ac45b914cbbb7373ed7d1 to your computer and use it in GitHub Desktop.
import React from "react";
import { screen, fireEvent, waitFor } from "@testing-library/react";
import UIFormRelatedURL from "./RelatedURL";
import { relatedUrlSchemeMock } from "../../Work/controlledVocabulary.gql.mock";
import { renderWithReactHookForm } from "../../../services/testing-helpers";
import userEvent from "@testing-library/user-event";
const props = {
codeLists: relatedUrlSchemeMock,
name: "relatedUrl",
label: "Related URL",
};
describe("Test component, error handling", () => {
// Here's an example of how to test that a React Hook Form element
// displays error messages, without submitting the form.
it("renders appropriate error messages with invalid url or select values", async () => {
const {
findByText,
getByTestId,
reactHookFormMethods,
} = renderWithReactHookForm(<UIFormRelatedURL {...props} />, {
toPassBack: ["setError"],
});
userEvent.click(getByTestId("button-add-field-array-row"));
await waitFor(() => {
// Here we manually manipulate the form, setting an error the same way React Hook Form does
reactHookFormMethods.setError("relatedUrl[0].url", {
type: "validate",
message: "Please enter a valid url",
});
});
expect(await findByText("Please enter a valid url"));
});
});
...
// And what the input being tested may look like...
<input
type="text"
name={`${itemName}.url`}
className={`input ${
errors[name] && errors[name][index].url
? "is-danger"
: ""
}`}
ref={register({
required: "Related URL is required",
validate: (value) =>
isUrlValid(value) || "Please enter a valid URL",
})}
defaultValue=""
data-testid={`related-url-url-input`}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment