-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwithTestId.tsx
More file actions
44 lines (36 loc) · 1.05 KB
/
withTestId.tsx
File metadata and controls
44 lines (36 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import React, { ComponentType, FC } from "react";
interface Options {
shouldWrapChildren?: boolean;
}
const TestIdWrapper: FC<{ testId: string }> = ({ testId, children }) => (
<div data-testid={testId}>{children}</div>
);
const withTestId = <P extends Record<string, any>>(
testId: string,
WrappedComponent?: ComponentType<P>,
options: Options = {}
): FC<P> => {
const { shouldWrapChildren = false } = options;
const displayName =
WrappedComponent?.displayName || WrappedComponent?.name || "Component";
const Wrapper: FC<P> = (props) => {
if (!WrappedComponent) {
return <TestIdWrapper testId={testId} />;
}
if (!shouldWrapChildren) {
return (
<TestIdWrapper testId={testId}>
<WrappedComponent {...props} />
</TestIdWrapper>
);
}
return (
<WrappedComponent {...props}>
<TestIdWrapper testId={testId}>{props.children}</TestIdWrapper>
</WrappedComponent>
);
};
Wrapper.displayName = `withTestId(${displayName})`;
return Wrapper;
};
export default withTestId;