Assertions in React Testing Library

Hi, in this post we are going to talk about Jest 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:

expect(element).toBeInTheDocument();
  • The expect() method that’s global in Jest, the argument this is what your assertion is assorting against; Jest will examine and see if that element meet the expectations.
  • .toBeInTheDocument() this is matcher this is what the assertion match is. The matcher in this case “toBeInTheDocument()” comes from Jest-DOM and sometimes there is an argument in the matcher.

Other examples of assertions:

expect(element.textContent).toBe('hola');
  • 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.
expect(myArray).toHaveLength(5);
  • The expect() method is holding an array as a parameter.
  • The matcher is .toHaveLength() and the parameter is number 5, means that if myArray have a length of 5 then the assertion will pass.

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

By Cristina Rojas.