Methods to get DOM

  1. Aria-label try not to use

    role and aria-label in css. It’s all about accessibility.

    aria-label="cancelbtn", will read cancelbtn directly. So aria-label is for reading. If there is no aria-label, the value of role will be pronounced. If there is no role, read the default role, the button tag in html. When both aria-label and role exist, role will be read after aria-label is read. If you write this, use the reader to test.

    Therefore, do not use role indiscriminately, the consequences are very serious. Many websites now have cookies, which are mandated by the GDPR. Europe and the United States will be fined.


  2. Get the source of the DOM method

    These method sources are all destructuring of render(<component>), such as:

    1
    2
    3
    const {getByLableText, getByRole, rerender, debug} = render(
    <FavoriteNumber />,
    )


  1. Websites and plugins to help get the DOM

    Website for testing elements: https://testing-playground.com/.

    Chrome plugin for testing elements: Testing Playground.


  1. getByRole().

    For testing, getByRole() is preferred. Its parameter is the text in html.


  1. getByTestId()

    The test can get the element with screen.getByTestId(“id”) . The id needs to be annotated with data-testid = {} in the body element. Everything that starts with data is useless to html, only for test.


  1. getByLabelText()

    Get the element using the id in the Label.


  2. queryByRole()

    This method is similar to getByRole(). The difference between them is that when the test component is not rendered, if the component is not found, the error message of getByRole() will be bad. And queryByRole() is designed for this situation.


Share