Unable to find an element with the text: “myText” error when using react-testing-library

后端 未结 1 1133

I\'m trying to use react-testing-library with React and Jest but one of my tests are failing and I think it has something to do with the regex on the classNam

相关标签:
1条回答
  • 2021-02-20 13:40

    getByText looks for the text inside a node. So in this example:

    <div class="foo">bar</div>
    

    the text is bar.

    getByAltText is the best way to find an image. Another way is to use getByTestId.

    What if you must find an element by class? In these cases, you can use container which is returned by render. container is just a DOM node so you can do

    const { container } = render(<MyComponent />)
    container.querySelector('.my-class')
    

    Note that you don't have to use toBeDefined(), you can use toBeInTheDocument() which is more idiomatic. Make sure you install jest-dom first.


    How to make a snapshot? Again, you can use container. In this case you want the first child.

    expect(container.firstChild).toMatchSnapshot()
    
    0 讨论(0)
提交回复
热议问题