SETTING UP TESTS FOR REACT NATIVE EXPO TYPESCRIPT

Introduction

Recently I decided to write tests for my Expo React Native app written in TypeScript. Having done this in React.js, I didn’t expect its native counterpart to be such a pain 😩.

I did the usual rounds — reading docs, scouring Stack Overflow, and still came up short. Thankfully, I stumbled upon the npm package expo-template-typescript-jest by elgsantos. That discovery was the game-changer.

This guide is for anyone trying to set up tests in a TypeScript + Expo + React Native environment without losing their mind. Let’s get into it.

1. Installing Dependencies

Here’s a list of the packages you’ll need:

  • react-test-renderer
  • jest
  • jest-expo
  • ts-jest
  • jest-coverage-badges
  • @types/jest
  • @types/react-test-renderer

Install them using your preferred package manager.

2. Setting Up Jest Configuration

Here's a sample jest.config.js you can use:

module.exports = {
  testEnvironment: 'jsdom',
  preset: 'jest-expo',
  globals: {
    'ts-jest': {
      tsconfig: {
        jsx: 'react',
      },
    },
  },
  transform: {
    '^.+\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js',
    '^.+\\.tsx?$': 'ts-jest',
  },
  testMatch: ['**/?(*.)+(spec|test).ts?(x)'],
  collectCoverageFrom: [
    '**/*.{ts,tsx}',
    '!**/coverage/**',
    '!**/node_modules/**',
    '!**/babel.config.js',
    '!**/jest.setup.js',
  ],
  moduleFileExtensions: ['js', 'ts', 'tsx'],
  transformIgnorePatterns: [
    'node_modules/(?!(jest-)?react-native|@react-native-community|expo(nent)?|react-navigation)',
  ],
  coverageReporters: ['json-summary', 'text', 'lcov'],
}

3. Updating tsconfig.json

Update your tsconfig.json file to make sure Jest and TypeScript play nicely together.

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "jsx": "react-native",
    "lib": ["dom", "esnext"],
    "moduleResolution": "node",
    "noEmit": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "strict": true,
    "esModuleInterop": true
  }
}

4. Writing Your First Test

Here's an example test for your App.tsx component:

import React from 'react'
import renderer from 'react-test-renderer'
import App from './App'

describe('<App />', () => {
  it('has 2 children', () => {
    const tree: any = renderer.create(<App />).toJSON()
    expect(tree?.children?.length).toBe(2)
  })
})

You can run your tests with:

npm test

Or, if you're using Yarn:

yarn test

Summary

With just a few configurations and the right packages, you can write and run unit tests in an Expo + TypeScript + React Native project.

I highly recommend checking out the full template here:

🔗 elgsantos/expo-template-typescript-jest


Hope this saves someone else from the hours of setup I went through! Happy testing! ✅