0
0
React Nativemobile~20 mins

Jest setup for unit tests in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Jest Test Setup
Set up Jest testing environment for a React Native app and create a simple unit test for a component.
Target UI
-------------------------
| Jest Test Setup Screen |
|-----------------------|
| Component renders text |
| Button to run tests   |
-------------------------
Configure Jest in React Native project
Create a simple functional component that displays text
Write a unit test to check if the component renders the correct text
Ensure test can be run with 'npm test' or 'yarn test'
Starter Code
React Native
import React from 'react';
import { Text, View } from 'react-native';

export default function Greeting() {
  // TODO: Return a View with a Text component that says 'Hello, Jest!'
  return null;
}
Task 1
Task 2
Task 3
Task 4
Solution
React Native
import React from 'react';
import { Text, View } from 'react-native';

export default function Greeting() {
  return (
    <View>
      <Text>Hello, Jest!</Text>
    </View>
  );
}

// __tests__/Greeting.test.js
import React from 'react';
import { render } from '@testing-library/react-native';
import Greeting from '../Greeting';

test('Greeting component renders correct text', () => {
  const { getByText } = render(<Greeting />);
  expect(getByText('Hello, Jest!')).toBeTruthy();
});

// package.json scripts section
// "scripts": {
//   "test": "jest"
// },

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

We implemented the Greeting component to return a View containing a Text element with the string "Hello, Jest!". This is the UI we want to test.

In the __tests__/Greeting.test.js file, we use @testing-library/react-native to render the component and check if the text "Hello, Jest!" is present. This confirms the component renders correctly.

The package.json script "test" runs Jest, and the jest.config.js file configures Jest for React Native, including necessary presets and transforms.

This setup allows running npm test or yarn test to execute the unit test and verify the component's output.

Final Result
Completed Screen
-------------------------
| Jest Test Setup Screen |
|-----------------------|
| Hello, Jest!           |
-------------------------
User runs 'npm test' or 'yarn test' in terminal
Jest runs the Greeting.test.js file
Test passes confirming the component renders 'Hello, Jest!' text
Stretch Goal
Add snapshot testing for the Greeting component
💡 Hint
Use 'toMatchSnapshot()' in your Jest test to save and compare the component's rendered output