asFragment
was the correct one.
It as actually a bug on the test. But it was a bit hard to see so I had to do a serialization first.
type MyComponentProps = { text: string }
function MyComponent({ text }: MyComponentProps) {
return <span data-testid="my-element">{text}</span>
}
const MyComponentWithRef = forwardRef<HTMLSpanElement, MyComponentProps>(({ text }, ref) => <span data-testid="my-ref-element" ref={ref}>{text}</span>)
describe("hoc", () => {
it("simple component should work as expected", async () => {
render(<MyComponent text="bar" />);
expect(screen.getByTestId("my-element")).toHaveTextContent("bar");
})
it("should work with simple component", () => {
const serializer = new XMLSerializer();
const HocMyComponent = withHoc<MyComponentProps, MyComponentProps, HTMLSpanElement>(MyComponent);
const { asFragment } = render(<HocMyComponent text="should be as is" />);
expect(screen.getByTestId("my-element")).toHaveTextContent("should be as is");
const renderedValue = serializer.serializeToString(asFragment());
const { asFragment: expectedAsFragment } = render(<span data-testid="my-element">should be as is</span>);
expect(renderedValue).toStrictEqual(serializer.serializeToString(expectedAsFragment()));
});
But once I figured out what was wrong in the test. The resulting test is
it("should work with simple component", () => {
const HocMyComponent = withHoc<MyComponentProps, MyComponentProps, HTMLSpanElement>(MyComponent);
const { asFragment } = render(<HocMyComponent text="should be as is" />);
expect(screen.getByTestId("my-element")).toHaveTextContent("should be as is");
const { asFragment: expectedAsFragment } = render(<span data-testid="my-element">should be as is</span>);
expect(asFragment()).toStrictEqual(expectedAsFragment());
});