Knowledge Base (Jest )
Please review knowledge base, if you cannot find the answer you are looking for? Reach out to our support team by opening forum thread.
- 1. Setting up Jest for testing React Native applications
-
Step 1: Install Jest and related dependencies
npm install --save-dev jest @testing-library/react-native react-test-renderer
Step 2: Create a Jest configuration file
// jest.config.js module.exports = { preset: '@testing-library/react-native', transform: { '^.+\\.js$': 'babel-jest', }, };
Step 3: Configure Babel for Jest
babel.config.js { "presets": ["module:metro-react-native-babel-preset"] }
Step 4: Add a script to run tests in
package.json
// package.json { "scripts": { "test": "jest" } }
Step 5: Run the tests
npm test
- 2. React Native TextInput Sample Code
-
some basic test cases for a React Native Text Input Component using Jest
// TextInputComponent.js
import React, { useState } from 'react'; import { TextInput, View, Button, Text } from 'react-native'; const MyTextInput = () => { const [text, setText] = useState(''); const handleInputChange = (inputText) => { setText(inputText); }; const handleButtonPress = () => { // Perform some action with the input text console.log(`Input Text: ${text}`); }; return ( <View> <TextInput placeholder="Type something..." value={text} onChangeText={handleInputChange} /> <Button title="Submit" onPress={handleButtonPress} /> </View> ); }; export default MyTextInput;
- 3. Handles input change
-
// TextInputComponent.test.js import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import MyTextInput from './TextInputComponent'; describe('MyTextInput component', () => { it('handles input change', () => { // Render the MyTextInput component const { getByPlaceholderText } = render(<MyTextInput />); const input = getByPlaceholderText('Type something...'); // Simulate entering text into the input fireEvent.changeText(input, 'Hello, World!'); // Assert that the input value reflects the entered text expect(input.props.value).toBe('Hello, World!'); }); });
Explanation:
-
Render the Component:
const { getByPlaceholderText } = render(<MyTextInput />);
: Rendering theMyTextInput
component and destructuring thegetByPlaceholderText
function from the returned object.
-
Get the Input Element:
const input = getByPlaceholderText('Type something...');
: UsinggetByPlaceholderText
to get the input element by its placeholder text.
-
Simulate Entering Text:
fireEvent.changeText(input, 'Hello, World!');
: Simulating entering the text 'Hello, World!' into the input.
-
Assertion:
expect(input.props.value).toBe('Hello, World!');
: Asserting that thevalue
prop of the input reflects the entered text. This ensures that theMyTextInput
component correctly handles and retains the entered input.
-
- 4. Executes button press
-
// TextInputComponent.test.js import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import MyTextInput from './TextInputComponent'; describe('MyTextInput component', () => { it('executes button press', () => { // Render the MyTextInput component const { getByPlaceholderText, getByText } = render(<MyTextInput />); const input = getByPlaceholderText('Type something...'); const button = getByText('Submit'); // Simulate entering text into the input fireEvent.changeText(input, 'Hello, World!'); // Simulate pressing the submit button fireEvent.press(button); }); });
Explanation:
-
Render the Component:
const { getByPlaceholderText, getByText } = render(<MyTextInput />);
: Rendering theMyTextInput
component and destructuring thegetByPlaceholderText
andgetByText
functions from the returned object.
-
Get Elements:
const input = getByPlaceholderText('Type something...');
: UsinggetByPlaceholderText
to get the input element by its placeholder text.const button = getByText('Submit');
: UsinggetByText
to get the button element by its text content.
-
Simulate Entering Text:
fireEvent.changeText(input, 'Hello, World!');
: Simulating entering the text 'Hello, World!' into the input.
-
Simulate Button Press:
fireEvent.press(button);
: Simulating pressing the submit button
-
- 5. Renders with default empty value
-
// TextInputComponent.test.js import React from 'react'; import { render } from '@testing-library/react-native'; import MyTextInput from './TextInputComponent'; describe('MyTextInput component', () => { it('renders with default empty value', () => { // Render the MyTextInput component const { getByPlaceholderText } = render(<MyTextInput />); const input = getByPlaceholderText('Type something...'); // Assert that the input value is an empty string by default expect(input.props.value).toBe(''); }); });
Explanation:
-
Render the Component:
const { getByPlaceholderText } = render(<MyTextInput />);
: Rendering theMyTextInput
component and destructuring thegetByPlaceholderText
function from the returned object.
-
Get the Input Element:
const input = getByPlaceholderText('Type something...');
: UsinggetByPlaceholderText
to get the input element by its placeholder text.
-
Assertion:
expect(input.props.value).toBe('');
: Asserting that thevalue
prop of the input is an empty string by default. This ensures that the component is initially rendered with an empty input value.
-
- 6. Handles empty input correctly
-
// TextInputComponent.test.js import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import MyTextInput from './TextInputComponent'; describe('MyTextInput component', () => { it('handles empty input correctly', () => { // Render the MyTextInput component const { getByPlaceholderText, getByText } = render(<MyTextInput />); const input = getByPlaceholderText('Type something...'); const button = getByText('Submit'); // Simulate a button press without entering any text fireEvent.press(button); // Assertions to check how the component handles empty input // Example assertions (customize based on your component's behavior): // 1. Check if an error message is displayed // const errorMessage = getByText('Please enter something.'); // expect(errorMessage).toBeTruthy(); // 2. Check if a specific callback function is not called // const mockCallback = jest.fn(); // expect(mockCallback).not.toHaveBeenCalled(); }); });
Explanation:
-
Render the Component:
const { getByPlaceholderText, getByText } = render(<MyTextInput />);
: Rendering theMyTextInput
component and destructuring thegetByPlaceholderText
andgetByText
functions from the returned object.
-
Get Elements:
const input = getByPlaceholderText('Type something...');
: UsinggetByPlaceholderText
to get the input element by its placeholder text.const button = getByText('Submit');
: UsinggetByText
to get the button element by its text content.
-
Simulate Button Press:
fireEvent.press(button);
: Simulating a button press without entering any text into the input.
-
Assertions:
- Add your specific assertions based on the behavior you expect when handling empty input. In the example, I've included two scenarios:
- Checking if an error message is displayed when no text is entered.
- Checking if a specific callback function is not called.
- Add your specific assertions based on the behavior you expect when handling empty input. In the example, I've included two scenarios:
-
- 7. Handles input with special characters
-
// TextInputComponent.test.js import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import MyTextInput from './TextInputComponent'; describe('MyTextInput component', () => { it('handles input with special characters', () => { const { getByPlaceholderText } = render(<MyTextInput />); const input = getByPlaceholderText('Type something...'); fireEvent.changeText(input, 'Special!@#$%^&*()_+-={}[]|:;"<>,.?/~`'); expect(input.props.value).toBe('Special!@#$%^&*()_+-={}[]|:;"<>,.?/~`'); }); });
Explanation:
-
Render the Component:
const { getByPlaceholderText } = render(<MyTextInput />);
: Rendering theMyTextInput
component and destructuring thegetByPlaceholderText
function from the returned object.
-
Get the Input Element:
const input = getByPlaceholderText('Type something...');
: UsinggetByPlaceholderText
to get the input element by its placeholder text.
-
Simulate Entering Special Characters:
fireEvent.changeText(input, 'Special!@#$%^&*()_+-={}[]|:;"<>,.?/~
');: Simulating entering a string with various special characters into the input using
fireEvent.changeText`.
-
Assertion:
expect(input.props.value).toBe('Special!@#$%^&*()_+-={}[]|:;"<>,.?/~
');: Asserting that the
valueprop of the input reflects the entered string with special characters. This checks whether the
MyTextInput` component correctly handles and retains input with special characters.
-
- 8. Renders without crashing
-
// TextInputComponent.test.js import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import MyTextInput from './TextInputComponent'; describe('MyTextInput component', () => { it('renders without crashing', () => { // Render the component const { getByPlaceholderText, getByText } = render(<MyTextInput />); // Get the input element by its placeholder text const input = getByPlaceholderText('Type something...'); // Get the button element by its text content const button = getByText('Submit'); // Assertions to check if the component renders without crashing expect(input).toBeInTheDocument(); expect(button).toBeInTheDocument(); expect(input).toBeVisible(); expect(button).toBeVisible(); }); });
Explanation:
-
Render the Component:
const { getByPlaceholderText, getByText } = render(<MyTextInput />);
: Rendering theMyTextInput
component and destructuring thegetByPlaceholderText
andgetByText
functions from the returned object.
-
Get Elements:
const input = getByPlaceholderText('Type something...');
: UsinggetByPlaceholderText
to get the input element by its placeholder text.const button = getByText('Submit');
: UsinggetByText
to get the button element by its text content.
-
Assertions:
expect(input).toBeInTheDocument();
: Asserting that the input element is in the document.expect(button).toBeInTheDocument();
: Asserting that the button element is in the document.expect(input).toBeVisible();
: Asserting that the input element is visible.expect(button).toBeVisible();
: Asserting that the button element is visible.
-
- 9. Displays an error message for invalid input
-
// TextInputComponent.test.js import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import MyTextInput from './TextInputComponent'; describe('MyTextInput component', () => { it('displays an error message for invalid input', () => { const { getByPlaceholderText, getByText } = render(<MyTextInput />); const input = getByPlaceholderText('Type something...'); const button = getByText('Submit'); fireEvent.changeText(input, 'Invalid Input'); fireEvent.press(button); }); });
Test Logic:
-
const errorMessage = getByText('Invalid input. Please try again.');
: Using thegetByText
function to get the element that should contain the error message. Adjust the text content based on what your actual error message is. -
expect(errorMessage).toBeTruthy();
: Asserting that theerrorMessage
element exists and is truthy. If the error message element is found, the test will pass; otherwise, it will fail.
-
- 10. Renders the submit button
-
// TextInputComponent.test.js import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import MyTextInput from './TextInputComponent'; describe('MyTextInput component', () => { it('renders the submit button', () => { const { getByText } = render(<MyTextInput />); const button = getByText('Submit'); expect(button).toBeTruthy(); }); });
Test Logic:
-
const { getByText } = render(<MyTextInput />);
: Rendering theMyTextInput
component and destructuring thegetByText
function from the returned object. This function allows you to select elements based on their text content. -
const button = getByText('Submit');
: Using thegetByText
function to get the button element with the text content 'Submit'. -
expect(button).toBeTruthy();
: Asserting that thebutton
element exists and is truthy. If the button element is found, the test will pass; otherwise, it will fail.
-