DEV Community

Cover image for React Testing Library, Setup, Why it is important in React?
Lukman Hossain
Lukman Hossain

Posted on Edited on

React Testing Library, Setup, Why it is important in React?

Introduction:

React Testing Library builds on top of DOM Testing Library by adding APIs for working with React components.

Install React Library:

Image description

Importance Of Testing:

  1. Catch Bugs Easily
  2. Increases Confidence in Application
  3. Speeds up QA Time
  4. Can Serve as Documentations

Types of Tests:

There are 3 types of Testing-

  1. Unit Tests
  2. Integration Tests
  3. End to End (E2E) Tests

Structure of Tests:

Package.Json file 1st Part

Image description

Package.Json file 2nd Part

Image description

Here is an example of a test that uses all of these and expect our json data to be rendered on our page and be defined.

Image description

Priority:

Priority is different ways

  1. Accessible by everyone
    • getByRole
    • getByLabelText
    • getByPlaceholderText
    • getByText

  2. Semantic Queries
    • getByAltText
    • getByTitle

  3. Test Id
    • getByTestId

Assertions:

The assertions will determine if the test pass or fail, they are essential part of the test.

Let’s see an example of the assertion syntax:

Image description

Others Example of assertions:

Image description

• In this case expect() method have the ‘text content of the element‘ as a parameter.
• Then the matcher is .toBe() and the parameter is a string ‘hola‘, so, if the text content of the element is equal to ‘hola’ then the assertion pass.

Image description

React Testing Library or apps with Jest:

Jest-DOM

Jest-DOM comes with ‘create-react-app’ and use the src/setupTests.js to import Jest-DOM before each test and this means that the Jest matchers are available ables for every test.
So the next examples are DOM-based matchers:
• toBeDisabled
• toBeEnabled
• toBeEmpty
• toBeEmptyDOMElement
• toBeInTheDocument
• toBeInvalid
• toBeRequired
• toBeValid
• toBeVisible
• toContainElement
• toContainHTML
• toHaveAttribute
• toHaveClass
• toHaveFocus
• toHaveFormValues
• toHaveStyle
• toHaveTextContent
• toHaveValue
• toHaveDisplayValue
• toBeChecked
• toBePartiallyChecked
• toHaveDescription

Happy Learning !!

Top comments (0)