DEV Community

Cover image for Jest for React Native
Afroze Kabeer Khan. M
Afroze Kabeer Khan. M

Posted on

Jest for React Native

This is an article on how to setup jest in react-native with support for vscode.

The base setup of react-native
npx react-native init unittest

Installing the additional dependencies
yarn add --dev @testing-library/react-native @testing-library/jest-native

Extend your jest config in package.json,

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

You're ready to write unit test cases for react-native, let's setup your vscode.

Intellisense is important for code completion, create a jsconfig.json file in your project root directory.
Add the following contents in it.

{
    "typeAcquisition": {
        "include": [
            "jest"
        ]
    }
}
Enter fullscreen mode Exit fullscreen mode

Install types to support autocompletion.
yarn add @types/jest

Lets add a plugin to vscode, which makes testing easier, Jest Test Explorer

Let's write some test cases.
Create a folder structure as below,

Folder structure

A Sample React Native component, Banner.js

import React from 'react';
import {View, Text} from 'react-native'

const Banner = () => {
  return (
    <View>
      <Text>Banner</Text>
    </View>
  )
}

export default Banner;

Enter fullscreen mode Exit fullscreen mode

A Sample test file for the component, Banner.test.js

import React from 'react'
import { render } from '@testing-library/react-native';

import Banner from './Banner'

describe('Banner', () => {
  it('renders correctly', () => {
    const { getByText } = render(<Banner />)
    const textField = getByText('Banner')
    expect(textField).toBeDefined()
  });
})

Enter fullscreen mode Exit fullscreen mode

After adding the file, you can see three options in your file, This provides us the ability to validate a single test case without having to write special commands, debug them.

options

It also gives us a look at the tree structure of all the test cases in your project and run them as a whole.
tree structure

So its a wrap, Hope you find this useful and effective to work with.

Talk to me on twitter droidmakk

Top comments (0)