Unit testing

React Native Testing Library is a testing library for React Native inspired by React Testing Library. Because React Native does not run in a browser environment, the core queries are implemented independently, unlike other wrappers that use DOM Testing Library as the base.

It provides light utility functions on top of react-test-renderer, in a way that encourages better testing practices.

Install library

yarn add --dev @testing-library/react-native  @testing-library/jest-native

Configuration

Create jest.config.json file configuration :

{
  "preset": "react-native",
  "setupFilesAfterEnv": ["@testing-library/jest-native/extend-expect"]
}

Write Tests

Create a file inside __tests__folder and start testing your components A simple unit test for a Counter Components.

import "react-native";
import React from "react";
import { fireEvent, render } from "@testing-library/react-native";

it("renders correctly", () => {
  // render component
  const { getByText } = render(<Counter />);

  // get buttons and text elements
  const decrement = getByText(/decrement/i);
  const increment = getByText(/increment/i);
  const counterText = getByText(/Current count:/i);

  // Make sure you have the right values
  expect(counterText.props.children).toEqual(["Current count: ", 0]);
  // trigger an event
  fireEvent.press(increment);
  expect(counterText.props.children).toEqual(["Current count: ", 1]);
  fireEvent.press(decrement);
  expect(counterText.props.children).toEqual(["Current count: ", 0]);
});

More Examples

🧑‍💻 Exercise

Test our Login Form to Make sure it :

  • renders correctly
  • should display required error when values are empty
  • should display matching error when email is invalid
  • should call login whit correct values when values are valid

👉 https://github.com/yjose/Tasker/commit/0dd56bf363e27d4e383b2251c3eae141216173e7

← FormsNavigation →