Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Fix useTestIds docs, add a few tests. #973

Merged
merged 1 commit into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/utils/useTestIds.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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" });
});
});
18 changes: 10 additions & 8 deletions src/utils/useTestIds.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { defaultTestId } from "src/utils/defaultTestId";

export type TestIds = Record<string, object>;

/**
* 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"
Expand All @@ -12,9 +16,9 @@
*
* ```tsx
* const { a, b } = props;
* const testIds = useTestIds(props);
* const tid = useTestIds(props);
*
* return <Foo {...testIds.foo />;
* return <Foo {...tid.foo} />;
* ```
*
* This allows components that embed the component to customize the prefix, i.e.
Expand All @@ -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<string, object>;

export function useTestIds(props: object, defaultPrefix?: string): Record<string, object> {
const prefix: string | undefined =
(props as any)["data-testid"] ||
Expand Down
Loading