0
0
React Nativemobile~10 mins

Jest setup for unit tests in React Native

Choose your learning style9 modes available
Introduction

Jest helps you check if your React Native code works right. Setting it up means you can find mistakes early and fix them fast.

When you want to check if a button click works as expected.
When you add a new feature and want to make sure it doesn't break old code.
When you want to test functions that handle data or calculations.
When you want to run tests automatically before sharing your app.
When you want to catch bugs before users see them.
Syntax
React Native
npm install --save-dev jest @testing-library/react-native @testing-library/jest-native react-test-renderer

// Add to package.json
"scripts": {
  "test": "jest"
}

// Create jest.config.js
module.exports = {
  preset: 'react-native',
  setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect'],
  transformIgnorePatterns: [
    'node_modules/(?!(react-native|@react-native|@react-navigation)/)'
  ]
};

Use npm install --save-dev to add testing tools only for development.

The jest.config.js file tells Jest how to work with React Native.

Examples
This command installs Jest and tools to test React Native components.
React Native
npm install --save-dev jest @testing-library/react-native @testing-library/jest-native react-test-renderer
This script lets you run tests by typing npm test in the terminal.
React Native
"scripts": {
  "test": "jest"
}
This config file sets up Jest to understand React Native code and adds helpful matchers for testing.
React Native
module.exports = {
  preset: 'react-native',
  setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect'],
  transformIgnorePatterns: [
    'node_modules/(?!(react-native|@react-native|@react-navigation)/)'
  ]
};
Sample App

This test checks if the button calls the function when pressed. It uses Jest and React Native Testing Library.

React Native
import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import { render, fireEvent } from '@testing-library/react-native';

function Button({ onPress, title }) {
  return (
    <TouchableOpacity onPress={onPress} accessibilityLabel="button">
      <Text>{title}</Text>
    </TouchableOpacity>
  );
}

test('Button calls onPress when pressed', () => {
  const onPressMock = jest.fn();
  const { getByA11yLabel } = render(<Button onPress={onPressMock} title="Click me" />);
  const button = getByA11yLabel('button');
  fireEvent.press(button);
  expect(onPressMock).toHaveBeenCalledTimes(1);
});
OutputSuccess
Important Notes

Always add accessibilityLabel to components to find them easily in tests.

Run npm test to start Jest and see test results.

Keep tests small and focused on one thing at a time.

Summary

Jest helps catch bugs early by running tests on your React Native code.

Install Jest and testing libraries, then add a config file to set it up.

Write simple tests to check if components behave as expected.