diff --git a/src/utils/useTestIds.test.tsx b/src/utils/useTestIds.test.tsx index dc86b5a90..628b996f3 100644 --- a/src/utils/useTestIds.test.tsx +++ b/src/utils/useTestIds.test.tsx @@ -15,4 +15,19 @@ describe("useTestIds", () => { const tid = useTestIds({ "data-testid": "firstName" }); expect({ ...tid }).toEqual({ "data-testid": "firstName" }); }); + + it("can use a label as a default prefix", () => { + const tid = useTestIds({}, "First Name"); + expect(tid.input).toEqual({ "data-testid": "firstName_input" }); + }); + + it("can use an optional enum as a default prefix", () => { + enum Color { + Blue = "Blue", + Green = "Green", + } + const colorProp = Color.Blue as Color | undefined; + const tid = useTestIds({}, colorProp); + expect(tid.input).toEqual({ "data-testid": "blue_input" }); + }); }); diff --git a/src/utils/useTestIds.tsx b/src/utils/useTestIds.tsx index e3a59ab82..b03f93ed3 100644 --- a/src/utils/useTestIds.tsx +++ b/src/utils/useTestIds.tsx @@ -1,7 +1,11 @@ +import { defaultTestId } from "src/utils/defaultTestId"; + +export type TestIds = Record; + /** * Provides a way to easily generate `data-testid`s. * - * The test ids are made of a `prefix` + `_` + `key`, where: + * The test ids are made of a `${prefix}_${key}`, where: * * - The prefix is the component name, like "profile", and * - The key is the specific DOM element that's being tagged, like "firstName" @@ -12,9 +16,9 @@ * * ```tsx * const { a, b } = props; - * const testIds = useTestIds(props); + * const tid = useTestIds(props); * - * return ; + * return ; * ``` * * This allows components that embed the component to customize the prefix, i.e. @@ -25,12 +29,10 @@ * - `firstName_errors` * - `lastName_input` * - `lastName_errors` - * - etc + * + * @param props the component's `props` object, which we'll scan for `data-testid` to use as the prefix + * @param defaultPrefix the default prefix to use if no `data-testid` is found on `props` */ -import { defaultTestId } from "src/utils/defaultTestId"; - -export type TestIds = Record; - export function useTestIds(props: object, defaultPrefix?: string): Record { const prefix: string | undefined = (props as any)["data-testid"] ||