简体   繁体   English

testing-library/react 中 toJSON 的等价物是什么?

[英]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@testing-library/react-native中,我有一个由render提供的名为toJSON的方法,我用它来比较结果 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 .我试图在@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.但结果是失败了,因为它缺少我的数据。

asFragment was the correct one. asFragment是正确的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM