reactjstestingtesting-library

What is the equivalent of toJSON in testing-library/react?


In @testing-library/react-native I have a method provided by render called toJSON which I use to compare the resulting output

    const { toJSON } = render(<HocText>simple string</HocText>);
    const { toJSON: expectedToJSON } = render(<Text>simple string</Text>);
    expect(toJSON()).toStrictEqual(expectedToJSON());

I am trying to find the equivalent of it in @testing-library/react.

I tried

    const { asFragment } = render(<HocMyComponent text="should be as is" />);
    const { asFragment: expectedAsFragment } = render(<span>should be as is</span>);
    expect(asFragment()).toStrictEqual(expectedAsFragment());

But the result was a failure because it is missing my data.


Solution

  • 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());
    });